Python的mutable值碎碎念
Python的mutable值碎碎念

Python的mutable值碎碎念
• 发表于 1年前
• 阅读 5
• 收藏 0
• 评论 0

>>> def test(a, b=[]):
...     b.append(a)
...     return b

>>> test(1)
[1]
>>> test(2)
[1, 2]
>>> test(3)
[1, 2, 3]

[另一方面，在嵌套函数中，python2的内层函数无法获取外层函数不可变变量，但可以访问可变变量，因此通常这样写

def test():

a = [1]

def t():

print a[0]

t()

——————————————————————————————————————————————

>>> a = [1,2,[12]]
>>> b = a
>>> a = [2,3,[23]]
>>> a
[2, 3, [23]]
>>> b
[1, 2, [12]]

>>> a = [1,2,[12]]
>>> b = a
>>> a[1] = 3
>>> a[2].append(3)
>>> b
[1, 3, [12, 3]]
>>>

>>> c = 1
>>> d = deepcopy(c)
>>> id(c),id(d)
(140569092332408, 140569092332408)

>>> a = (1,2)
>>> b = deepcopy(a)
>>> id(a),id(b)
(4482226008, 4482226008)
>>> a = (1,[12])
>>> b = deepcopy(a)
>>> id(a),id(b),id(a[0]),id(b[0]),id(a[1]),id(b[1])
(4482223208, 4482225792, 140569092332408, 140569092332408, 4482452008, 4482450280)

————————————————————————————————————————————

immutable数据是可以自定义的，只要重写继承的object的__setattr__和__delattr__

1. class Immutable(object):
2.     def __setattr__(self, *args):
3.         raise TypeError("can't modify the value of immutable instance")
4.
5.     __delattr__ = __setattr__
6.
7.     def __init__(self, value):
8.          super(Immutable, self).__setattr__("value", value)

×