Reputation: 39079
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
Upvotes: 3
Views: 7327
Reputation: 24034
You can do this by using class attributes rather than instance attributes:
class Base(object):
foo = 5
class Derived(Base):
"""A class derived from Base.
>>> bar = Base()
>>> print bar.foo
5
>>> foobar = Derived()
>>> print foobar.foo
6
>>> print foobar.__class__.__base__.foo
5
>>> foobar.__class__.__base__.foo = 7
>>> bar.foo
7
"""
foo = 6
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 foo
equal to 5 or 6. This code, on the other hand, creates foo
attributes 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.
Upvotes: 1
Reputation: 41306
No, there is no way to access it, since the attribute is overriden. The classes share the same __dict__
storage.
If you want to avoid clash of identically named private attributes in subclasses, you can use self.__foo
, which will expand to self._ClassName__foo
, but you normally shouldn't need that.
Upvotes: 2