consider the following python code
class Base(object):
def __init__(self):
self.foo = 5
class Derived(Base):
def __init__(self):
Base.__init__(self)
self.foo = 6
bar = Base()
print bar.foo
foobar = Derived()
print foobar.foo
Can I access the foo in the base class from foobar. In C++ we can use Base::, how about Python? Any simple way?
Thanks
You can do this by using class attributes rather than instance attributes:
It’s important to understand the distinction. The code in your question creates classes that, when instantiated, grant to the newly created instance attributes of
fooequal to 5 or 6. This code, on the other hand, createsfooattributes of the classes themselves that are accessible from any instances thereof.This is actually implemented by using a dictionary for each instance, and another dictionary for each ancestor class. If Python doesn’t find a requested attribute in the instance dictionary, it looks in the class dictionary for that instance; if it’s not not found there, Python will continue to search each base class for that attribute.