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

在Python中,静态方法如何访问类变量?,python,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:

这就是我的代码的样子

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
如何访问
@staticmethod
中的
邀请\u消息

试试:

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
在其静态方法的范围内。

刚刚实现,我需要
@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

您可以阅读它

您可以通过
InviteManager.INVITE\u MESSAGE
访问它,但更简洁的解决方案是将静态方法更改为类方法:

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

(或者,如果您的代码真的像它看起来那么简单,您可以用模块中的一组函数和常量替换整个类。模块就是名称空间。)

您可以使用
InviteManager.INVITE\u MESSAGE
InviteManager.haven\u INVITED\u MESSAGE
访问您的属性,而无需更改其声明中的任何内容。

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

使用静态方法时,不会使用self关键字,因为self关键字用于表示类的实例或使用类的实例变量。事实上,一个使用类名称的例子如下:

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!

或者把它变成模块级函数。@delnan:是的。但是,有时您需要一个类或静态方法,特别是在涉及继承或duck类型的情况下。您知道python为什么允许通过
staticmethod
访问
类变量吗?如果是这样,为什么我们需要
classmethod
?如果
classmethod
staticmethod
都可以访问类变量,那么它们之间的用例有什么不同?