Python中的继承和内部类? [英] Inheritance and inner classes in Python?
问题描述
在以下代码类中 B
从类 A继承
,我期待这个。我还希望内部类 yay
属性 B.Foo
的行为方式相同但不行。
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.
如何使 B.Foo
从类 A
alice 属性>?我需要 B
中的内部子类 Foo
具有属性 alice
和 bob
。
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
.
谢谢。
>>> 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'
推荐答案
B.Foo.alice
之所以给你一个错误是因为 Foo
属性之间没有任何联系class 一个
和 Foo
类 B
的属性。
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
.
在 B
中,属性 Foo
有一个类对象值完全替换从 A
继承的类对象值。
In B
, attribute Foo
has a class object value that completely replaces class object value inherited from A
.
这应该修复它:
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.
如果类 B
,我们有:
-
yay
从A继承的值True
的属性 -
nay
属性值False
。 -
Foo
具有类对象的属性。
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.
这篇关于Python中的继承和内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!