The Python Oracle

Access static variable from static method

This video explains
Access static variable from static method

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Romantic Lands Beckon

--

Chapters
00:00 Question
00:42 Accepted answer (Score 26)
01:05 Answer 2 (Score 16)
01:33 Thank you

--

Full question
https://stackoverflow.com/questions/1123...

Accepted answer links:
[Not in Python.]: https://stackoverflow.com/questions/1360...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #oop #staticmethods #staticvariables

#avk47



ACCEPTED ANSWER

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




ANSWER 2

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