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.

1
  • 1
    Why are you trying to use super() in a class definition body in the first place? Commented May 15, 2014 at 21:29

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.