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'
A class defined in another class is known as an inner class or nested class. If an object is created using child class means inner class then the object can also be used by parent class or root class.
Inheritance in Python Inheritance is a powerful feature in object oriented programming. It refers to defining a new class with little or no modification to an existing class. The new class is called derived (or child) class and the one from which it inherits is called the base (or parent) class.
Inner classesA inner class declared in the same outer class (or in its descendant) can inherit another inner class.
inner classes are in the same file, whereas subclasses can be in another file, maybe in another package. You cannot get an instance of an inner class without an instance of the class that contains it.
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:
yay
attribute that has value True
inherited from A.nay
attribute that has value False
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With