python中的自引用类定义 [英] Self Referencing Class Definition in python
问题描述
有没有办法从类声明中引用类名?示例如下:
is there any way to reference a class name from within the class declaration? an example follows:
class Plan(SiloBase):
cost = DataField(int)
start = DataField(System.DateTime)
name = DataField(str)
items = DataCollection(int)
subPlan = ReferenceField(Plan)
我有一个元类来读取这些信息并进行一些设置,而基类实现了一些常见的保存内容.我希望能够创建这样的递归定义,但到目前为止,在我的实验中,我一直无法获得我想要的效果,通常会遇到计划未定义"错误.我明白发生了什么,类的名称不在类内的范围内.
i've got a metaclass that reads this information and does some setup, and the base class implements some common saving stuff. i would love to be able to create recursive definitions like this, but so far in my experimentation i have been unable to get the effect i desire, usually running into a "Plan is not defined" error. I understand what is happening, the name of the class isn't in scope inside the class.
推荐答案
我有一个元类来读取这些信息并进行一些设置
i've got a metaclass that reads this information and does some setup
大多数使用元类的框架都提供了解决此问题的方法.例如,Django:
Most frameworks that use metaclasses provide a way to resolve this. For instance, Django:
subplan = ForeignKey('self')
subplan = SelfReferenceProperty()
诸如在稍后添加附加属性或使用 __new__
等解决方案的问题在于,大多数 ORM 元类都希望类属性在创建类时存在.
The problem with solutions like tacking an additional property on later or using __new__
is that most ORM metaclasses expect the class properties to exist at the time when the class is created.
这篇关于python中的自引用类定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!