Python有类原型(或前向声明)吗? [英] Does Python have class prototypes (or forward declarations)?
问题描述
我在一个文件中有一系列Python类。
I have a series of Python classes in a file. Some classes reference others.
我的代码是这样的:
class A():
pass
class B():
c = C()
class C():
pass
尝试运行,我得到 NameError:name'C'is not defined
。公平了,但有什么办法使它工作,或者我必须手动重新排序我的类适应?在C ++中,我可以创建一个类原型。 Python有一个等价的?
Trying to run that, I get NameError: name 'C' is not defined
. Fair enough, but is there any way to make it work, or do I have to manually re-order my classes to accommodate? In C++, I can create a class prototype. Does Python have an equivalent?
(我实际上在使用Django模型,但我尝试不复杂的事情)。
(I'm actually playing with Django models, but I tried not complicate matters).
推荐答案
在Python中,你不会创建一个原型本身,但你需要了解类属性和实例级属性之间的区别。在上面的例子中,你在类B上声明一个类属性,而不是一个实例级属性。
In Python you don't create a prototype per se, but you do need to understand the difference between "class attributes" and instance-level attributes. In the example you've shown above, you are declaring a class attribute on class B, not an instance-level attribute.
这是你正在寻找的东西: / p>
This is what you are looking for:
class B():
def __init__(self):
self.c = C()
这篇关于Python有类原型(或前向声明)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!