假設你想要的是「在第一次函數調用時只初始化一次的變量」,Python語法中就沒有這種東西。但也有方法可以得到類似的結果:
1 - 使用一個全球性的。需要注意的是在Python中,「全球性」的真正意義的全球到模塊',而不是「全球的過程」:
_number_of_times = 0
def yourfunc(x, y):
global _number_of_times
for i in range(x):
for j in range(y):
_number_of_times += 1
2 - 在一個類中總結你的代碼,並使用一個類屬性(即:一個屬性這是所有實例共享的)。:
class Foo(object):
_number_of_times = 0
@classmethod
def yourfunc(cls, x, y):
for i in range(x):
for j in range(y):
cls._number_of_times += 1
請注意,我用了一個classmethod
因爲這個代碼片斷不會從一個實例
3需要什麼 - 總結你的代碼放在一個類,使用實例屬性和方法提供了捷徑:
class Foo(object):
def __init__(self):
self._number_of_times = 0
def yourfunc(self, x, y):
for i in range(x):
for j in range(y):
self._number_of_times += 1
yourfunc = Foo().yourfunc
4 - 寫一個可調用的類,並提供了捷徑:
class Foo(object):
def __init__(self):
self._number_of_times = 0
def __call__(self, x, y):
for i in range(x):
for j in range(y):
self._number_of_times += 1
yourfunc = Foo()
條
4之二 - 使用類屬性和元類
class Callable(type):
def __call__(self, *args, **kw):
return self._call(*args, **kw)
class yourfunc(object):
__metaclass__ = Callable
_numer_of_times = 0
@classmethod
def _call(cls, x, y):
for i in range(x):
for j in range(y):
cls._number_of_time += 1
5 - 做一個「創意」使用功能的默認參數在模塊的進口被實例化一次:
def yourfunc(x, y, _hack=[0]):
for i in range(x):
for j in range(y):
_hack[0] += 1
仍然有一些其他可能的解決方案/黑客攻擊,但我認爲你現在可以看到大局。
編輯:給予操作的澄清,即「假設你有一個遞歸函數與默認參數,但如果有人實際上試圖給你的功能多一個參數可能是災難性的」,它看起來像OP真正想要什麼是這樣的:
# private recursive function using a default param the caller shouldn't set
def _walk(tree, callback, level=0):
callback(tree, level)
for child in tree.children:
_walk(child, callback, level+1):
# public wrapper without the default param
def walk(tree, callback):
_walk(tree, callback)
其中,順便說一句,證明我們真的然而,另一個問題XY ...
聲明該變量的外部for循環。 – 2014-10-29 12:51:33
這不是唯一聲明局部變量'static'的東西。請告訴我們你想用Python中的變量做什麼,以及你實際想要解決什麼問題([閱讀關於XY問題](http://meta.stackexchange.com/questions/66377/what-is-在-XY-問題))。 – 2014-10-29 12:54:19
請注意,Python的範圍比C++少得多,因此對此類構造的需求較少。此代碼的Python版本中的'number_of_times'不會被限制在inner for循環中。 – chepner 2014-10-29 12:54:35