您的位置:首页 > 编程语言 > Python开发

python的可变和不可变对象

2016-04-29 14:59 621 查看
python的对象分为可变对象(mutable)和不可变对象(immutable)

不可变对象(immutable)包括:常数、字符串、元组和不可变集合(frozensets)

可变对象包括:列表、字典、自定义类对象(也可用特殊方法定义为不可变类)

所谓不可变对象,就是不能动态修改对象的值或成员

例如:

a=1

print id(a)

a+=1

print id(a)

这两次打印的ID值并不同,这说明a的地址空间发生了变化,而并没有在原有地址空间中执行加操作,因为常数1是个不可变对象,不能对其值进行修改。

再例如:

a=[1,2]

print id(a)

a+=[3]

print id(a)

这两次打印的ID值是相同的,因为列表是可变变量(mutable)

定制immutable的数据类型

定制immutable的数据类型,那么你必须重写object的__setattr__和__delattr__方法,例如:

view
plaincopy
to clipboardprint?

class Immutable(object):  

    def __setattr__(self, *args):  

        raise TypeError("can't modify the value of immutable instance")  

  

    __delattr__ = __setattr__  

  

    def __init__(self, value):  

         super(Immutable, self).__setattr__("value", value)  

我们可以做如下测试

view
plaincopy
to clipboardprint?

>>> x = Immutable("baiyang")  

>>> x.value  

'baiyang'  

# 重新赋值  

>>> x.value = "ibaiyang"  

Traceback (most recent call last):  

  File "<stdin>", line 1, in <module>  

  File "<stdin>", line 3, in __setattr__  

TypeError: can't modify immutable instance  

# 删除  

>>> del x.value  

Traceback (most recent call last):  

  File "<stdin>", line 1, in <module>  

  File "<stdin>", line 3, in __setattr__  

TypeError: can't modify immutable instance  

</stdin></module></stdin></stdin></module></stdin> 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: