从静态方法访问静态变量 [英] Access static variable from static method

查看:111
本文介绍了从静态方法访问静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从静态方法访问静态变量:

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)

如何在不将grrrr传递给方法的情况下执行此操作?这是真正的面向对象吗?..

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

nameself.name之类的东西似乎都不起作用:

Anything like name or self.name seems not working:

NameError: global name 'name' is not defined

NameError: global name 'self' is not defined

推荐答案

使用@classmethod代替@staticmethod.在写完问题后才发现它.

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

在许多语言(C ++,Java等)中,静态"和类"方法是同义词. 不在Python中.

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

这篇关于从静态方法访问静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆