Paolo Paolo - 1 month ago 13
Python Question

Inheritance and inner classes in Python?

In the following code class

B
has inherited
yay
attribute from class
A
, I expected this. I'd also expect that inner class
B.Foo
behaves the same way but it doesn't.

How to make
B.Foo
to inherit
alice
attribute from class
A
? I need that the inner subclass
Foo
in
B
has both the attributes
alice
and
bob
.

Thanks.

>>> class A:
... yay = True
... class Foo:
... alice = True
...
>>> class B(A):
... nay = False
... class Foo:
... bob = False
>>> B.yay
True
>>> B.Foo.alice
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class Foo has no attribute 'alice'

Answer

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.

Comments