Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access static variable from static method

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
like image 604
Dmitry Isaev Avatar asked Jun 27 '12 19:06

Dmitry Isaev


2 Answers

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.

like image 62
Dmitry Isaev Avatar answered Oct 31 '22 13:10

Dmitry Isaev


def get_msg():
    return "hello " + Messenger.name

You can't use self.name because self is not defined. self is a naming convention for the first parameter of non-static or non-classmethod methods. It points to the object on which you called the method. Since your method is static, you don't need an object to call it on.

like image 38
Ioan Alexandru Cucu Avatar answered Oct 31 '22 14:10

Ioan Alexandru Cucu