Python 是否有类原型(或前向声明)? [英] Does Python have class prototypes (or forward declarations)?

查看:38
本文介绍了Python 是否有类原型(或前向声明)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个文件中有一系列 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.

这就是你要找的:

class B():
    def __init__(self):
        self.c = C()

这篇关于Python 是否有类原型(或前向声明)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆