开发者

Problem with static variable

I'm trying to declare static variable and now my code is:

class StaticClass:
    varA = 'hello'

    @staticmethod
    def staticMethod():
        varA='bye'

Result of code below is hello. Why not 'bye' ?

StaticClass.staticMethod()

pr开发者_运维知识库int StaticClass.varA


The code in staticMethod() assigns the string bye to the local variable varA, then returns, dropping the local variable. An assignment inside a function always creates local variables in Python. A staticmethod in Python has no means of accessing the class at all -- you need a classmethod for this purpose:

class StaticClass:
    var_a = 'hello'

    @classmethod
    def cls_method(cls):
        cls.var_a = 'bye'


It's because the varA you define in StaticClass.staticMethod() is in the method's namespace, not in the class namespace, if you want to access the class' varA you should do something like:

StaticClass.varA = 'bye'

By the way, you don't need to create a staticmethod to do this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜