Can a Python inner class be a subclass of its own outer class?

和自甴很熟 提交于 2021-02-05 11:15:49

问题


This...

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

... 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.


回答1:


As per OPs request, posting as an answer.

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

  2. 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.

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




回答2:


You can not do this the normal way and probably should not do this.

For those who have a valid reason to attempt something similar, there is a workaround by dynamically changing the superclass of A.B after A is fully defined (see https://stackoverflow.com/a/9639512/5069869).

This is probably terrible code, a big hack and should not be done, but it works under certain conditions (see linked answer)

class T: pass
class A(object):
  def a(self):
    return "Hallo a"
  class B(T):
    def b(self):
      return "Hallo b"
A.B.__bases__ = (A,)
b=A.B()
assert isinstance(b, A)
assert b.a()=="Hallo a"

Now you can even do something weird like x = A.B.B.B.B()



来源:https://stackoverflow.com/questions/39077623/can-a-python-inner-class-be-a-subclass-of-its-own-outer-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!