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

2024-05-23 17:18:05 发布

您现在位置: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


Tags: 代码youmessagedbreturnemailsessionnot
3条回答

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

您可以以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在它的静态方法的范围内。

相关问题 更多 >