0

我正在尝试编写一个 Datastore 模型类,该类具有一个创建对象并将其一次性添加到 Datastore 的函数。这是我目前拥有的(不起作用):

class Channel(db.Model):
    name = db.StringProperty(required = True)
    subscriber_list = db.ListProperty(users.User)

    def addChannelWithName(name):
        channel = Channel()
        channel.name = name
        channel.put()

从这里我得到的问题是传递给 addChannelWithName() 的第一件事是假设是一个 Channel 实例,但当然我正在尝试做一个通道实例不应该存在。它应该在此函数期间创建。我应该如何去做这项工作?有没有办法将此函数保留为 Channel 的方法,或者这应该是一个与类完全分离的函数?还是我应该做点别的?非常感谢!

4

2 回答 2

2

Or you could make it a class method or static method. That way if your using the model somewhere else you don't need to import the seperate function from the module.

class Channel(db.Model):
    name = db.StringProperty(required = True)
    subscriber_list = db.ListProperty(users.User)

    @classmethod
    def addChannelWithName(cls,name):
        channel = cls()
        channel.name = name
        channel.put()

or a static method and omit cls.

You would call it as Channel.addChannelWithName(name) If you use a class or static method I would drop the "Channel" bit from the method name as it's redundant. ie Channel.addWithName(name) because you only call it from the class.

于 2013-04-14T03:08:19.470 回答
0

我认为最简单的解决方案是使其成为顶级的独立函数而不是方法。(你可以把它变成一个静态方法,或者——通过改变调用签名——一个类方法,但我真的看不出这样做有什么好处。)

于 2013-04-14T01:41:15.760 回答