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
?
Static Methods can access class variables(static variables) without using object(instance) of the class, however non-static methods and non-static variables can only be accessed using objects. Static methods can be accessed directly in static and non-static methods.
Static methods serve mostly as utility methods or helper methods, since they can't access or modify a class's state. Static methods can access and modify the state of a class or an instance of a class.
Use class_name dot variable_name to access a class variable from a class method in Python. Use instance to access variables outside the class.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With