Python中的继承和内部类? [英] Inheritance and inner classes in Python?

查看:187
本文介绍了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 ,我们有:


  1. yay 从A继承的值 True 的属性

  2. nay 属性值 False

  3. Foo 具有类对象的属性。

  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.

这篇关于Python中的继承和内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆