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

时间:2013-08-25 16:47: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

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

NameError: global name 'INVITE_MESSAGE' is not defined

如何在INVITE_MESSAGE内访问@staticmethod

5 个答案:

答案 0 :(得分:38)

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

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

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

答案 1 :(得分:6)

尝试:

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属于staticmethods。

答案 2 :(得分:2)

刚才意识到,我需要@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

您可以阅读here

答案 3 :(得分:2)

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

答案 4 :(得分:0)

简单地,了解类级别变量/方法和实例级别变量/方法的概念。

在使用静态方法时,您不会使用 self 关键字,因为 self 关键字用于表示类的实例或使用类的实例变量。实际上,一个使用 class_name ,请参见以下示例:

class myclass():
    msg = "Hello World!"

    @staticmethod
    def printMsg():
        print(myclass.msg)



myclass.printMsg() #Hello World!
print(myclass.msg) #Hello World!
myclass.msg = "Hello Neeraj!"
myclass.printMsg() #Hello Neeraj!
print(myclass.msg) #Hello Neeraj!