我有20年的C++经验,现在学习Python还有些困难。
现在我想要一个拥有自己“静态”变量(不是静态类变量)的方法(一个类内的函数)。
可能一个伪代码示例可以更好地说明我想要什么。
最初的回答:
class dummy:
@staticmethod
def foo():
foo.counter += 1
print "You have called me {} times.".format(foo.counter)
foo.counter = 0
注意1:我只是为了简单起见使用了@staticmethod
,但这不相关。
注意2:这会崩溃并出现AttributeError: 'staticmethod' object has no attribute 'counter'
,但正如我上面所说,这只是伪代码,以阐明我的目标。
我已经学会了这个在类外部可以运行:
Original Answer翻译成"最初的回答"
def foo():
foo.counter += 1
print "You have called me {} times.".format(foo.counter)
foo.counter = 0
但对于成员函数,同样的技巧似乎不起作用。
最后一分钟的信息,我只能使用Python 2.7(不是我的选择)。
是否有任何合法可靠的方法可以拥有一个作用域仅限于成员函数作用域的持续变量(或常量)?
一些相关链接:
"What is the Python equivalent of static variables inside a function?": https://dev59.com/oHVC5IYBdhLWcg3wfhGL#279586 "There are no function-level static variables in Python": https://code-maven.com/slides/python-programming/static-variable 先行致谢。
staticmethod
,方法将能够自由地修改该变量。 - undefined_
表示这些是实现细节,不建议进行修改。) - undefined