Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a member in base class in Python?

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

like image 829
szli Avatar asked Jun 18 '26 18:06

szli


2 Answers

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.

like image 132
Lukáš Lalinský Avatar answered Jun 21 '26 07:06

Lukáš Lalinský


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.

like image 39
intuited Avatar answered Jun 21 '26 08:06

intuited