How can static method access class variable in Python?
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.
Just realized, I needed @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
You can read about it here