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'
The reason why
B.Foo.alice
gave you an error is because there's no connection betweenFoo
attribute of classA
andFoo
attribute of classB
.In
B
, attributeFoo
has a class object value that completely replaces class object value inherited fromA
.This should fix it:
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:yay
attribute that has valueTrue
inherited from A.nay
attribute that has valueFalse
.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 classA
, but just because both of them have inner classFoo
doesn't tell us anything about their inheritance.If you want
B.Foo
to have the attributes fromA.Foo
, you need to makeB.Foo
inherit fromA.Foo
:Foo
is it's own class. It does not inherit fromA
. Because of this, it does not have any fields ofA
. The fact that is nested in a subclass ofA
does not change anything.