python - How to understand this doc -
this the python docs. don't understand this, can give examples?
if class defines slot defined in base class, instance variable defined base class slot inaccessible (except retrieving descriptor directly base class). renders meaning of program undefined. in future, check may added prevent this.
i tried make example of failed. when run program below prints 1
, variable not inaccessible. when be?
class base(object): __slots__ = 'a' def __init__(self): self.a = 1 class subclass(base): __slots__ = 'a' def __init__(self): super(subclass, self).__init__() print self.a subclass()
when run program below prints 1, variable not inaccessible.
you have two a
instance variables here. 1 defined base
not accessible through attribute access; object of type subclass
, accesses self.a
, including 1 inside base.__init__
, go instance variable defined subclass
.
if retrieve base.a
descriptor manually, can access slot defined base
:
>>> x = subclass() 1 >>> base.a.__get__(x) traceback (most recent call last): file "<stdin>", line 1, in <module> attributeerror: >>> base.a.__set__(x, 2) >>> base.a.__get__(x) 2 >>> subclass.a.__get__(x) 1
as can see, base.a
, subclass.a
independent, despite sharing same name.
Comments
Post a Comment