静态方法如何在Python中访问类变量?

day*_*mer 45 python

这就是我的代码

class InviteManager():
    ALREADY_INVITED_MESSAGE = "You are already on our invite list"
    INVITE_MESSAGE = "Thank you! we will be in touch soon"

    @staticmethod
    @missing_input_not_allowed
    def invite(email):
        try:
            db.session.add(Invite(email))
            db.session.commit()
        except IntegrityError:
            return ALREADY_INVITED_MESSAGE
        return INVITE_MESSAGE
Run Code Online (Sandbox Code Playgroud)

当我运行我的测试时,我明白了

NameError: global name 'INVITE_MESSAGE' is not defined
Run Code Online (Sandbox Code Playgroud)

我怎样才能进入INVITE_MESSAGE里面@staticmethod

Fre*_*Foo 42

你可以访问它InviteManager.INVITE_MESSAGE,但更简洁的解决方案是将静态方法更改为类方法:

@classmethod
@missing_input_not_allowed
def invite(cls, email):
    return cls.INVITE_MESSAGE
Run Code Online (Sandbox Code Playgroud)

(或者,如果你的代码真的很简单,你可以用模块中的一堆函数和常量替换整个类.模块是命名空间.)


Mac*_*Gol 7

尝试:

class InviteManager():
    ALREADY_INVITED_MESSAGE = "You are already on our invite list"
    INVITE_MESSAGE = "Thank you! we will be in touch soon"

    @staticmethod
    @missing_input_not_allowed
    def invite(email):
        try:
            db.session.add(Invite(email))
            db.session.commit()
        except IntegrityError:
            return InviteManager.ALREADY_INVITED_MESSAGE
        return InviteManager.INVITE_MESSAGE
Run Code Online (Sandbox Code Playgroud)

InviteManager是静态方法的范围.


Moh*_*nan 6

它比所有这些都简单得多:

刚刚添加__class__到类变量中。就像这样:

return __class__.ALREADY_INVITED_MESSAGE
        return __class__.INVITE_MESSAGE
Run Code Online (Sandbox Code Playgroud)

无需提及 ClassName (InviteManager),也无需使用classmethod


day*_*mer 5

刚刚意识到,我需要@classmethod

class InviteManager():
    ALREADY_INVITED_MESSAGE = "You are already on our invite list"
    INVITE_MESSAGE = "Thank you! we will be in touch soon"

    @classmethod
    @missing_input_not_allowed
    def invite(cls, email):
        try:
            db.session.add(Invite(email))
            db.session.commit()
        except IntegrityError:
            return cls.ALREADY_INVITED_MESSAGE
        return cls.INVITE_MESSAGE
Run Code Online (Sandbox Code Playgroud)

你可以在这里读到它