Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - reference inner class from other inner class

I am trying to reference an inner class from another inner class. I have tried both :

class Foo(object):

  class A(object):
    pass

  class B(object):
    other = A

and

class Foo(object):

  class A(object):
    pass

  class B(object):
    other = Foo.A

with respective results:

Traceback (most recent call last):
  File "python", line 1, in <module>
  File "python", line 6, in Foo
  File "python", line 7, in B
NameError: name 'A' is not defined

and

Traceback (most recent call last):
  File "python", line 1, in <module>
  File "python", line 6, in Foo
  File "python", line 7, in B
NameError: name 'Foo' is not defined

Is this possible?

like image 813
crunk1 Avatar asked Feb 12 '17 08:02

crunk1


People also ask

How do I access an inner class from another class?

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass. InnerClass innerObject = outerObject.

How do you use a class from another class in Python?

Example: First, we create a class and then the constructor of the class. After creating a class, we will create another class within that class, the class inside another class will be called an inner class.

Can inner class have inner class?

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class.

Can you call a class within a class python?

You can access the inner class in the outer class using the self keyword. So, you can quickly create an instance of the inner class and perform operations in the outer class as you see fit. You can't, however, access the outer class in an inner class.


1 Answers

This is not possible, since everything you define in a class becomes a valid member only in an instance of that class, unless you define a method with @staticmethod, but there is no such property for a class.

So, this won't work either:

class Foo(object):
    x = 10

    class A(object):
        pass

    class B(object):
        other = x

This will work, but it is not what you intended:

class Foo(object):
  x = 10

  class A(object):
    pass

  class B(object):
    def __init__(self):
        self.other = Foo.A

f = Foo()
print(f.B().other)

The output is:

<class '__main__.Foo.A'>

The reason this works is that the methods (in this case __init__) are evaluated when the object is created, while assignment before the __init__ are evaluated while the class is read and interpreted.

You can get about the same thing you want by simply define all the classes inside a module of their own. The importing the module, makes it an object whose fields are the classes you define in it.

like image 165
Israel Unterman Avatar answered Nov 08 '22 18:11

Israel Unterman