3

Would there be a simple way to fix this error while keeping all 3 levels?

Deriving ClassA from object does not help.

Thanks in advance!

>>> class classA:
...     class classB(object):
...         def __init__(self):
...             self.b = 3
...         class classC(classA.classB):
...             def __init__(self):
...                 super(classC, self).__init__()
...                 self.c = 4
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in classA
  File "<stdin>", line 5, in classB
NameError: name 'classA' is not defined
8
  • 7
    Why would you want to do this? Commented Jan 9, 2013 at 15:08
  • class names will be shorter and code will be more readable Commented Jan 9, 2013 at 15:09
  • also, wanted to understand why thid=s does not work; maybe I miss some important concept Commented Jan 9, 2013 at 15:10
  • 2
    classA.classB.classC is no way shorter than classC... Commented Jan 9, 2013 at 15:10
  • @glglgl Maybe he saves one or another prefix with this. Commented Jan 9, 2013 at 15:10

2 Answers 2

8

No. At the time you define classC, classA does not exist yet.

It is only created after its body is fully executed. (The dict created from the body's execution is one parameter for the class creation call class = type('classname', (superclass_1, superclass_2, superclass_3), said_dict}).)

The easiest way would be defining them at the same level.

If absolutely needed, you can modify them later:

class classA:
    pass
class classB(object):
    def __init__(self):
        self.b = 3
class classC(classB):
    def __init__(self):
        super(classC, self).__init__()
        self.c = 4
classA.classB = classB
classB.classC = classC
Sign up to request clarification or add additional context in comments.

1 Comment

It might be useful to add to your answer an explanation of why classA cannot exist until all of the statements in the class body have been executed.
-1

Maybe something like this would work:

class classA:
    pass

class classB(object):
    def __init__(self):
        self.b = 3
classA.classB = classB

class classC(classA.classB):
    def __init__(self):
        super(classC, self).__init__()
        self.c = 4

classA.classB.classC = classC

2 Comments

Apart from makeing the last line more verbose, this doesn't add anything to @glglgl's answer.
@Duncan, you are right but when I posted it glglgl's answer didn't have the code

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.