在 Python 中引用类
我对 Python(用于应用程序引擎)感到有些困扰。我对它相当陌生(更习惯Java),但我一直很享受......直到现在。
下面这个不行!
class SomeClass(db.Model):
item = db.ReferenceProperty(AnotherClass)
class AnotherClass(db.Model):
otherItem = db.ReferenceProperty(SomeClass)
据我所知,似乎没有办法让它发挥作用。抱歉,如果这是一个愚蠢的问题。希望如果是这样的话,我会得到一个快速的答复。
提前致谢。
I'm having a spot of bother with Python (using for app engine). I'm fairly new to it (more used to Java), but I had been enjoying....until now.
The following won't work!
class SomeClass(db.Model):
item = db.ReferenceProperty(AnotherClass)
class AnotherClass(db.Model):
otherItem = db.ReferenceProperty(SomeClass)
As far as I am aware, there seems to be no way of getting this to work. Sorry if this is a stupid question. Hopefully if that is the case, I will get a quick answer.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Python 中查看“class”关键字的一种方法是在脚本的初始执行期间简单地创建一个新的命名范围。因此,您的代码会抛出 NameError: name 'AnotherClass' is not Defined 异常,因为 Python 在执行以下命令时尚未执行
class AnotherClass(db.Model):
行self.item = db.ReferenceProperty(AnotherClass)
行。解决这个问题最直接的方法是:将这些值的初始化移动到类的 __init__ 方法(构造函数的 Python 名称)中。
One way to view the "class" keyword in Python is as simply creating a new named scope during the initial execution of your script. So your code throws a NameError: name 'AnotherClass' is not defined exception because Python hasn't executed the
class AnotherClass(db.Model):
line yet when it executes theself.item = db.ReferenceProperty(AnotherClass)
line.The most straightforward way to fix this: move the initializations of those values into the class's
__init__
method (the Python name for a constructor).如果您的意思是它不起作用,因为每个类都想引用另一个类,请尝试以下操作:
如果有任何适当的元类魔法,它会与某些元类魔法发生冲突......但值得一试。
If you mean it won't work because each class want to reference the other, try this:
It conflicts with some metaclass magic if there is any in place ... worth a try though.