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 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()
As per OPs request, posting as an answer.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With