0

Is it possible to access a class object or its inner class object from a class static variable in python3?

class OuterClass:
 all_subclasses = {
 # is it possible to access the OuterClass from a class static variable
 'innerclass1': OuterClass.InnerClass1
 }
 @classmethod
 isInnerClass(cls, identifier: str):
 return identifier.lower() in cls.all_subclasses
 class InnerClass1:
 def __init__(self):
 pass

If not, what will be alternative for this?

asked Sep 10, 2019 at 14:37
2
  • If you define InnerClass1 before all_subclasses, you can refer to it with just InnerClass1. You can't refer to OuterClass in it's own definition though, becasue it doesn't exist yet. Commented Sep 10, 2019 at 14:46
  • @PatrickHaugh: you are right. Python is interpreted language, i got confused with the compiled language. If you want to put that as answer, i can accept it as correct. Commented Sep 10, 2019 at 15:01

1 Answer 1

1

You can refer to attributes of the class directly in the class definition, as long as the reference comes after the definition:

class A:
 class B:
 pass
 x = B
print(A.x)
# <class '__main__.A.B'>

This has some caveats. For reasons that are very complicated, you can't use class attributes directly in a comprehension in the class definition:

class A:
 class B:
 pass
 x = [B for _ in range(5)] # NameError: name 'B' is not defined

You also can't refer to the class itself in it's own definition:

class A:
 x = A # NameError: name 'A' is not defined

This is because class definition is basically another way of creating a type object

class A:
 x = 1
A = type('A', (object,), {'x': 1})

And it makes total sense both that you can't use an object before it's created and that you can't refer to it by a name it hasn't been assigned to yet.

It's important to note that this all applies only to the class definition itself, that is to say all of the code that gets executed directly as the class is created. Code that gets executed later, like method definitions, can refer to the class like any other code or through type(self)

answered Sep 10, 2019 at 15:19

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.