inheritance - Trouple accessing python superclass attributes -
this question has answer here:
i have 2 classes loosely take form below:
class foo: def __init__(self, foo): self.__foo = foo class bar(foo): def bar(self): print self.__foo when try invoke bar method on instance of bar, fails.
b = bar('foobar') b.bar() result:
traceback (most recent call last): file "foobar.py", line 14, in <module> b.bar() file "foobar.py", line 10, in bar print self.__foo attributeerror: bar instance has no attribute '_bar__foo' my understanding code should work based on two other questions, why doesn't it?
simple. __foo contains 2 underscores in beginning, it's assumed class-private method , it's transformed _classname__method.
when request access attribute named such on bar object asks bar class if has method (not foo class), self.__foo same self._bar__foo.
from documentation:
when identifier textually occurs in class definition begins 2 or more underscore characters , not end in 2 or more underscores, considered private name of class. private names transformed longer form before code generated them. transformation inserts class name, leading underscores removed , single underscore inserted, in front of name. example, identifier __spam occurring in class named ham transformed _ham__spam.
if modify code slightly
class foo: def __init__(self, foo): self.__foo = foo assert hasattr(self, '_foo__foo'), 'attribute has been created' class bar(foo): def bar(self): assert hasattr(self, '_foo__foo'), 'no errors, inheritance' assert statements not cause assertionerrors.
add __getattribute__ method bar class capture requests bar objects:
class bar(foo): def bar(self): print('accessing __foo bar') print(self.__foo) def __getattribute__(self, name): print('requested', name) return super().__getattribute__(name) b = bar('foobar') b.bar() there 3 lines (apart attributeerror) in output:
requested bar accessing __foo bar requested _bar__foo # attributeerror follows as can see, if attribute requesting has 2 leading underscores, python renaming on fly.
Comments
Post a Comment