I am learning OOP in python, and I am surprised to find in another post that a parent class can access a class variable defined in child, like the example below. I can understand that child can access a class variable defined in parent bc of inheritance (or is it not inheritance but something else?). What makes this possible and does it imply a pool of class variables that a subclass can adds to (and its superclasses can access) when it inherits from a superclass?
class Parent(object):
def __init__(self):
for attr in self.ATTRS: // accessing class variable defined in child?
setattr(self, attr, 0)
class Child(Parent):
#class variable
ATTRS = ['attr1', 'attr2', 'attr3']
def __init__(self):
super(Child, self).__init__()
self.selfis a direct instance ofChildnotParent, hence it can access those stuff. That's how attribute lookup works.selfin Parent class you are referring to?selfis the same instance in both places - it is an instance (an object produced from a class) of whatever class you used to instantiate it (Childin this case). From the point ofChild, it's an instance of itself. From the point ofParent, it's an instance of one of its subclasses.selfalways means "an instance of myself or my super- or subclasses" - so yes, methods on the parent class do have access to instance members (attributes or methods) of its subclasses. I recommend Raymond Hettinger's talk Python's Class Development Toolkit on this topic.