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?

Yingding Wang
  • 450
  • 3
  • 14
  • 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. – Patrick Haugh Sep 10 '19 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. – Yingding Wang Sep 10 '19 at 15:01

1 Answers1

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)

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96