How can static method access class variable in Python?

This is what my code looks like

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

When I run my tests, I see

NameError: global name 'INVITE_MESSAGE' is not defined

How can I access INVITE_MESSAGE inside @staticmethod ?


You can access it as InviteManager.INVITE_MESSAGE , but a cleaner solution is to change the static method to a class method:

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

(Or, if your code is really as simple as it looks, you can replace the whole class with a bunch of functions and constants in a module. Modules are namespaces.)


Try:

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

The InviteManager is in the scope of it's staticmethods.


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

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

上一篇: 我怎样才能有一个Django信号调用模型方法?

下一篇: 静态方法如何在Python中访问类变量?