简体   繁体   中英

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

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.

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 AB 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 = ABBBB()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM