本文介绍了Python 内部类可以是它自己的外部类的子类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这...

class A(object):
    class B(A):
        def __init__(self):
            pass

... 抛出NameError: name 'A' is not defined".

... throws "NameError: name 'A' is not defined".

是否有正确的语法来实现这一点,或者我必须使用像这样的变通方法?

Is there proper syntax to accomplish this, or must I use workarounds, like this?

class A(object):
    pass
class _B(A):
    pass
A.B = _B

先验是非常可取的.谢谢.

The prior is strongly preferable. Thank you.

推荐答案

根据 OP 的要求,作为答案发布.

As per OPs request, posting as an answer.

  1. 这是一个内部类,而不是一个子类.

  1. That's an inner class, not a subclass.

不,内部类不能继承(不扩展)它的外部类,因为在定义内部类时外部类没有完全定义.

No, an inner class can't inherit (not extend) its outer class because the outer class is not fully defined while defining the inner class.

您的解决方法不是解决方法,因为它没有内部类.你混淆了子类和内部类

Your workaround is not a work around, as it doesn't have an inner class. You are confusing subclasses and inner classes

这篇关于Python 内部类可以是它自己的外部类的子类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 12:21