静态方法如何在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

当我运行我的测试时,我看到了

NameError: global name 'INVITE_MESSAGE' is not defined

如何访问INVITE_MESSAGE里面@staticmethod


您可以将其作为InviteManager.INVITE_MESSAGE访问,但更InviteManager.INVITE_MESSAGE解决方案是将静态方法更改为类方法:

@classmethod
@missing_input_not_allowed
def invite(cls, email):
    return cls.INVITE_MESSAGE

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


尝试:

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

InviteManager处于静态方法的范围内。


您可以使用InviteManager.INVITE_MESSAGEInviteManager.ALREADY_INVITED_MESSAGE访问您的属性,而无需更改其声明中的任何内容。

链接地址: http://www.djcxy.com/p/9181.html

上一篇: How can static method access class variable in Python?

下一篇: Should I put my helper functions inside or outside the class?