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.
加载中,请稍侯......
精彩评论