Maison >développement back-end >Tutoriel Python >关于python中“赋值就是建立一个对象的引用”,大家怎么看?Python一切皆为对象又是什么意思?
为什么我觉得好不方便啊......
比如如下的代码:
<span class="n">x</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">]</span> <span class="n">y</span><span class="o">=</span><span class="n">x</span> <span class="n">y</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">=</span><span class="mi">4</span> <span class="k">print</span> <span class="n">x</span> <span class="o">>></span> <span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="mi">4</span> <span class="mi">2</span> <span class="mi">3</span> <span class="mi">4</span><span class="p">]</span>
a = 258在Python看来就是:
创建一个PyIntObject对象,值为258;a是一个指向PyObject的指针,将a指向此PyIntObject对象之所以能这么干就和 @蓝色的答案解释的一样,所有的PyObject都有同样的头部。 在Python中有些对象是可以在原处进行改变的(即可变对象),这种对象包括了列表、字典、集合和一些自定义的对象。而对于整数和字符串等不可变对象是不会存在题主所说的问题。比如:
<code class="language-python"><span class="o">>>></span> <span class="n">a</span> <span class="o">=</span> <span class="mi">123</span>
<span class="o">>>></span> <span class="n">b</span> <span class="o">=</span> <span class="n">a</span>
<span class="o">>>></span> <span class="n">a</span> <span class="o">=</span> <span class="mi">321</span>
<span class="o">>>></span> <span class="k">print</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span>
<span class="mi">321</span> <span class="mi">123</span>
</code>
问题的关键是,你写下y=x时,其实并没有新建一个y,而是一个类似c++中引用的机制,具体可以这样看: