Inheritance and inner classes in Python? Inheritance and inner classes in Python? python python

Inheritance and inner classes in Python?


The reason why B.Foo.alice gave you an error is because there's no connection between Foo attribute of class A and Foo attribute of class B.

In B, attribute Foo has a class object value that completely replaces class object value inherited from A.

This should fix it:

class B(A):    nay = False    class Foo(A.Foo):        bob = False

In general, it helps, at least for me, to think of a class body contents as a sequence of attributes with certain assigned values.

In case of class B, we have:

  1. yay attribute that has value True inherited from A.
  2. nay attribute that has value False.
  3. Foo attribute that has class object.

Class methods are also attributes that have callable objects as values.


Inheritance is a per-class thing. In your code class B inherits from class A, but just because both of them have inner class Foo doesn't tell us anything about their inheritance.

If you want B.Foo to have the attributes from A.Foo, you need to make B.Foo inherit from A.Foo:

class B(A):    class Foo(A.Foo):        bob = False


Foo is it's own class. It does not inherit from A. Because of this, it does not have any fields of A. The fact that is nested in a subclass of A does not change anything.