Python-从其他内部类引用内部类 [英] 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
和
class Foo(object):
class A(object):
pass
class B(object):
other = Foo.A
具有相应结果:
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
和
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
这可能吗?
推荐答案
这是不可能的,因为您在类中定义的所有内容仅在该类的实例中才成为有效成员,除非您使用@staticmethod
定义方法,但类没有此类属性.
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.
因此,这也不起作用:
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)
输出为:
<class '__main__.Foo.A'>
之所以可行,是因为在创建对象时会评估方法(在本例中为__init__
),而在读取和解释类时会评估__init__
之前的赋值.
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.
这篇关于Python-从其他内部类引用内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!