ca2longoria
ca2longoria

Reputation: 372

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.

Upvotes: 3

Views: 2898

Answers (2)

Bernhard
Bernhard

Reputation: 2251

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()

Upvotes: 2

DeepSpace
DeepSpace

Reputation: 81604

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

Upvotes: 1

Related Questions