Python - reference inner class from other inner class

南楼画角 提交于 2020-01-02 07:42:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/42185472/python-reference-inner-class-from-other-inner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!