Access static variable from static method

Dmitry Isaev picture Dmitry Isaev · Jun 27, 2012 · Viewed 13.6k times · Source

I want to access a static variable from a static method:

#!/usr/bin/env python
class Messenger:
    name = "world"
    @staticmethod
    def get_msg(grrrr):
        return "hello " + grrrr.name

print Messenger.get_msg(Messenger)

How to do it without passing grrrr to a method? Is this the true OOP?..

Anything like name or self.name seems not working:

NameError: global name 'name' is not defined

and

NameError: global name 'self' is not defined

Answer

Dmitry Isaev picture Dmitry Isaev · Jun 27, 2012

Use @classmethod instead of @staticmethod. Found it just after writing the question.

In many languages (C++, Java etc.) "static" and "class" methods are synonyms. Not in Python.