I'm having a spot of bother with Python (using for app engine). I'm fairly new to it (more us开发者_JS百科ed 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.
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)
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.
精彩评论