python - Confused about self in derived class and relation to base class member variables -
in code sample below using self.number in derived class, b, , number defined in (the base class). if data member defined in way in base class, accessible derived class?
i using python 2.7. correct way refer base object member variables?
class a(object): def __init__(self, number): self.number = number print "a __init__ called number=", number def printme(self): print self.number class b(a): def __init__(self, fruit): super(b, self).__init__(1) self.fruit = fruit print "b __init__ called fruit=", fruit def printme(self): print self.number cl1 = a(1) cl1.printme() cl2 = b("apple") cl2.printme()
unless in subclass eliminate it, yes. attributes assigned python objects added object's __dict__
(except relatively rare cases slots used or __setattr__
overridden non-standard), , implicit first argument bound member method going same methods originating child or parent class. vanilla instance attributes (though not methods or class attributes) not bound in way specific class definition, object instance belong.
the 1 caveat statement attributes names beginning double underscores. they'll still added __dict__
, accessible, have been name mangled, accessible outside defining class if retrieved using mangled transformation of attribute name.
Comments
Post a Comment