python tips - Python可变对象和不可变对象

且看如下例子:

>>> l = [1, 2, 3]
>>> ll = l
>>> ll.remove(1)
>>> l
[2, 3]
>>> 
>>> l = [1, 2, 3]
>>> ll = l[:]
>>> ll.remove(1)
>>> l
[1, 2, 3]
>>> 

是不是有点大吃一惊,跟c 语言怎么不一样呢?!

 

>>>a = [1]
>>>b = a 
>>>b[0] = 2
>>>a
[2]

列表是可变对象类型,因此传递的时候,变量名b绑定的内存地址与a绑定的内存地址是同一地址。

 

>>> x = 1
>>> y = 1
>>> x is y
True
>>>

数值为不可变类型,x与y指向的是数值为1的同一内存地址。

 

对于类来说也是如此:

class b:
    x = []
    def set(self):
        self.x.append(1)
    def get(self):
        return self.x

for i in range(3):
    a = b()
    print b.__dict__
    a.set()
    print a.get()

结果:

{'x': [], '__module__': '__main__', 'set': <function set at 0x7f89a319bcf8>, '__doc__': None, 'get': <function get at 0x7f89a319bd70>}
[1]
{'x': [1], '__module__': '__main__', 'set': <function set at 0x7f89a319bcf8>, '__doc__': None, 'get': <function get at 0x7f89a319bd70>}
[1, 1]
{'x': [1, 1], '__module__': '__main__', 'set': <function set at 0x7f89a319bcf8>, '__doc__': None, 'get': <function get at 0x7f89a319bd70>}
[1, 1, 1]
 

 

python中,万物皆对象。python中不存在所谓的传值调用,一切传递的都是对象的引用,也可以认为是传址。

python中,对象分为可变(mutable)和不可变(immutable)两种类型。

组(tuple)、数值型(number)、字符串(string)均为不可变对象,而字典型(dictionary)和列表型(list)的对象是可变对象。

>>>a = 1 #将名字a与内存中值为1的内存绑定在一起
>>>a = 2 #将名字a与内存中值为2的内存绑定在一起,而不是修改原来a绑定的内存中的值,这时,内存中值为1的内存地址引用计数-1,当引用计数为0时,内存地址被回收
>>>b = a #变量b执行与a绑定的内存
>>>b = 3 #创建一个内存值为3的内存地址与变量名字b进行绑定。这是a还是指向值为2的内存地址。
>>>a,b
>>>(2,3)

 

python函数参数的默认值与此的关系及例子,详见 python tips - 注意 python 函数参数的默认值http://www.cnblogs.com/congbo/archive/2012/11/29/2794413.html

 

参考: 

http://thomaschen2011.iteye.com/blog/1441254

http://www.cnblogs.com/evening/archive/2012/04/11/2442788.html

posted @ 2012-11-20 16:38  congbo  阅读(4550)  评论(0编辑  收藏  举报