如果 namedtuple 是不可变的,为什么它有一个 _replace 方法?
If a namedtuple is immutable, why does it have a _replace method?
请考虑此代码:
>>> point = namedtuple('point', ('x', 'y'))
>>> p1 = point(3,4)
point(x=3, y=4)
>>> id(p1)
2881782633456 # address in memory
>>> p1._replace(x = 78)
point(x=78, y=4)
>>> id(p1)
2881782633456 # same as before.
好像我就地改变了 namedtuple
即它是一个可变对象。但它到处都说 tuple
s 和 namedtuple
s 都是不可变对象。我很困惑。
再者,如果是不可变对象,为什么会有_replace
方法?
因为你没有赋值回来,所以替换这一行:
p1._replace(x = 78)
与:
pi = p1._replace(x = 78)
为了与众不同。
Tuple
绝对是不可变的。如果你打印 p1,即使在 _replace
函数之后也是一样的。
>>> point = namedtuple('point', ('x', 'y'))
>>> p1 = point(3,4)
>>> p1
point(x=3, y=4) #same before _replace
>>> p1._replace(x = 78)
point(x=78, y=4)
>>> p1
point(x=3, y=4) #same after _replace
那你为什么有_replace?
它旨在 return 命名元组的新实例用新值替换指定字段。它不会改变实际的元组本身。该操作是短暂的。
_replace 方法创建了一个新的命名元组,它不会改变原来的元组,所以不变性得以保留。
来自docs:
Return a new instance of the named tuple replacing specified fields with new values
请考虑此代码:
>>> point = namedtuple('point', ('x', 'y'))
>>> p1 = point(3,4)
point(x=3, y=4)
>>> id(p1)
2881782633456 # address in memory
>>> p1._replace(x = 78)
point(x=78, y=4)
>>> id(p1)
2881782633456 # same as before.
好像我就地改变了 namedtuple
即它是一个可变对象。但它到处都说 tuple
s 和 namedtuple
s 都是不可变对象。我很困惑。
再者,如果是不可变对象,为什么会有_replace
方法?
因为你没有赋值回来,所以替换这一行:
p1._replace(x = 78)
与:
pi = p1._replace(x = 78)
为了与众不同。
Tuple
绝对是不可变的。如果你打印 p1,即使在 _replace
函数之后也是一样的。
>>> point = namedtuple('point', ('x', 'y'))
>>> p1 = point(3,4)
>>> p1
point(x=3, y=4) #same before _replace
>>> p1._replace(x = 78)
point(x=78, y=4)
>>> p1
point(x=3, y=4) #same after _replace
那你为什么有_replace? 它旨在 return 命名元组的新实例用新值替换指定字段。它不会改变实际的元组本身。该操作是短暂的。
_replace 方法创建了一个新的命名元组,它不会改变原来的元组,所以不变性得以保留。
来自docs:
Return a new instance of the named tuple replacing specified fields with new values