[Tutor] How to access an instance variable of a superclass from an instance of the subclass?

Steven D'Aprano steve at pearwood.info
Thu Feb 23 05:40:14 EST 2017


On Wed, Feb 22, 2017 at 10:25:58PM -0600, boB Stepp wrote:
> I am trying to wrap my head around the mechanics of inheritance in
> Python 3.

Here is a simplified picture of how inheritence usually works in Python.

For an instance `spam`, when you look up an attribute (which includes 
methods), Python checks the following places *in this order*:

- attributes attached to spam itself ("instance attributes");

- attributes attached to spam's class ("class attributes");

- attributes attached to any parent classes (class attributes
  of superclasses).


(The actual rules are much more complex, but this will do for starters.)

If no such attribute is found, Python will try calling the class 
__getattr__ (if any) or superclass __getattr__, and if that doesn't 
exist or fails, Python will raise AttributeError.

How do class attributes normally get set? In the class definition:

class MyClass:
    attribute = None


How do instance attributes normally get set? In the __init__ method:

class MyClass:
    def __init__(self):
        self.attribute = None


If the __init__ method does get run, it doesn't get the chance to create 
the instance attributes. So if you have a subclass that defines 
__init__, you need to allow the superclass' __init__ to run too.



-- 
Steve


More information about the Tutor mailing list