Access static variable from static method

醉酒当歌 提交于 2019-12-04 02:48:43

问题


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

回答1:


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.




回答2:


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 you're method is static, you don't need an object to call it on.



来源:https://stackoverflow.com/questions/11233729/access-static-variable-from-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!