0

クラスメソッドを使用してプロパティのデフォルトを設定するモデルがあります。

class Organisation(db.Model):
    name=db.StringProperty()
    code=db.StringProperty(default=generate_code())

    @classmethod
    def generate_code(cls):
        import random
        codeChars='ABCDEF0123456789'
        while True: # Make sure code is unique
            code=random.choice(codeChars)+random.choice(codeChars)+\
                    random.choice(codeChars)+random.choice(codeChars)
            if not cls.all().filter('code = ',code).get(keys_only=True):
                return code

しかし、NameErrorが発生します:

NameError: name 'generate_code' is not defined

generate_code()にアクセスするにはどうすればよいですか?

4

3 に答える 3

4

コメントで述べたように、私はクラスメソッドを使用してファクトリとして機能し、そこから常にエンティティを作成します。それは物事をよりシンプルに保ち、あなたが望む振る舞いを得るための厄介なフックはありません。

これが簡単な例です。

class Organisation(db.Model):
    name=db.StringProperty()
    code=db.StringProperty()

    @classmethod
    def generate_code(cls):
        import random
        codeChars='ABCDEF0123456789'
        while True: # Make sure code is unique
            code=random.choice(codeChars)+random.choice(codeChars)+\
                    random.choice(codeChars)+random.choice(codeChars)
            if not cls.all().filter('code = ',code).get(keys_only=True):

        return code

    @classmethod
    def make_organisation(cls,*args,**kwargs):
        new_org = cls(*args,**kwargs)
        new_org.code = cls.generate_code()
        return new_org
于 2012-08-14T05:47:36.080 に答える
0
import random

class Test(object):

    def __new__(cls):
        cls.my_attr = cls.get_code()
        return super(Test, cls).__new__(cls)

    @classmethod
    def get_code(cls):
        return random.randrange(10)

t = Test()
print t.my_attr
于 2012-08-14T05:26:25.013 に答える
-1

クラス名を指定する必要があります。Organisation.generate_code()

于 2012-08-14T05:09:19.040 に答える