Reputation: 1691
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?
Upvotes: 1
Views: 993
Reputation: 181745
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.
Upvotes: 2
Reputation: 78690
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.
Upvotes: 2
Reputation: 280456
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.
Upvotes: 8