Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can static method access class variable in Python?

Tags:

python

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?

like image 793
daydreamer Avatar asked Aug 25 '13 16:08

daydreamer


People also ask

Can a static method access class variables?

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.

Can a static method access class 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.

How do you access a class variable in Python?

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.


1 Answers

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.)

like image 191
Fred Foo Avatar answered Sep 27 '22 22:09

Fred Foo