27

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

2 Answers 2

34

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

So to access a static variable within a static method of the class, I have to prefix the class name to the static variable I am accessing, like you have shown in your answer?
@RaynerDaCruz if you access it in a @staticmethod, then yes, you need to prefix the class name. If it's a @classmethod, then you can also use the cls argument of your method. Difference is well described here: medium.com/school-of-code/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.