0

Consider the following code:

>>> class A:
...    k = 1
...
>>> class B(A):
...     k = super(B, cls).k
...
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "<console>", line 2, in B1
NameError: name 'B' is not defined

Why is this causing the error and what is the best way to get around it? Thanks.

jazzblue
  • 2,411
  • 4
  • 38
  • 63

1 Answers1

3

super() can only be used in a method, not in the class definition. It needs access to the class MRO, which is not yet known when the B class body is being built.

Even better, B isn't bound yet when the class is being defined! That doesn't happen until after the class body has been executed; you first need a class body before you can create a class object.

Just don't override k:

class A:
    k = 1

class B(A):
    pass

and B.k is inherited from A.

or reference it directly; you know exactly what base classes you have, when defining a class, after all:

class A:
    k = 1

class B(A):
    k = A.k
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343