Suppose I have:
from collections import namedtuple
NT = namedtuple('name', ['x'])
Can someone explain the difference between:
NT.x = 3var = NT(x=3)
I can change NT.x to anything (mutable) but var.x is immutable. Why is that the case?
Suppose I have:
from collections import namedtuple
NT = namedtuple('name', ['x'])
Can someone explain the difference between:
NT.x = 3 var = NT(x=3) I can change NT.x to anything (mutable) but var.x is immutable. Why is that the case?
NT is not a namedtuple. NT is a class. Its instances are namedtuples.
You cannot reassign x on an instance. While you can technically mess with the x on the class, that will break attribute access for the x attribute of the instances, as the x on the class is a descriptor that instances rely on to implement the corresponding instance attribute.
namedtuple is a class factory.
NT(x=3) gives you an instance of your freshly created class.
NT.x =3 sets an attribute on the class itself.
NT.x is an attribute of the class NT, not of an instance of that class:
>>> NT.x
<property object at 0x7f2a2dac6e58>
Its presence is just telling you that instances of NT have a property called x. See also this question.