在 Python 中引用类

发布于 2024-08-11 08:12:52 字数 336 浏览 3 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

分開簡單 2024-08-18 08:12:52

在 Python 中查看“class”关键字的一种方法是在脚本的初始执行期间简单地创建一个新的命名范围。因此,您的代码会抛出 NameError: name 'AnotherClass' is not Defined 异常,因为 Python 在执行以下命令时尚未执行 class AnotherClass(db.Model):self.item = db.ReferenceProperty(AnotherClass) 行。

解决这个问题最直接的方法是:将这些值的初始化移动到类的 __init__ 方法(​​构造函数的 Python 名称)中。

class SomeClass(db.Model):
  def __init__(self):
    self.item = db.ReferenceProperty(AnotherClass)

class AnotherClass(db.Model):
  def __init__(self):
    self.otherItem = db.ReferenceProperty(SomeClass)

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 the self.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).

class SomeClass(db.Model):
  def __init__(self):
    self.item = db.ReferenceProperty(AnotherClass)

class AnotherClass(db.Model):
  def __init__(self):
    self.otherItem = db.ReferenceProperty(SomeClass)
自此以后,行同陌路 2024-08-18 08:12:52

如果您的意思是它不起作用,因为每个类都想引用另一个类,请尝试以下操作:

class SomeClass(db.Model):
  item = None

class AnotherClass(db.Model):
  otherItem = db.ReferenceProperty(SomeClass)

SomeClass.item = db.ReferenceProperty(AnotherClass)

如果有任何适当的元类魔法,它会与某些元类魔法发生冲突......但值得一试。

If you mean it won't work because each class want to reference the other, try this:

class SomeClass(db.Model):
  item = None

class AnotherClass(db.Model):
  otherItem = db.ReferenceProperty(SomeClass)

SomeClass.item = db.ReferenceProperty(AnotherClass)

It conflicts with some metaclass magic if there is any in place ... worth a try though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文