#要實現累加,關鍵在於數據存在哪兒,怎么使每次累加的都是同一個變量 行為像靜態變量
#前兩種都是數據存到類的成員變量,
# 類利用__call__
class foo:
def __init__(self, n=0):
self.n = n
def __call__(self, i):
self.n += i
return self.n
a=foo()
print (a(1),a(2),a(3),a(4)) #1 3 6 10
#函數中定義類,返回一個實例的成員函數
def foo2 (n=0):
class acc:
def __init__ (self, s):
self.s = s
def inc (self, i):
self.s += i
return self.s
return acc (n).inc
a=foo2()
print (a(1),a(2),a(3),a(4))
#閉包 私以為最好用
def foo3():
count = 0
def f(n):
nonlocal count
count+=n
return count
return f
a= foo3()
print (a(1),a(2),a(3),a(4))
# 奇淫技巧吧,又不是c,沒必要管什么堆內存
def foo4 (i, L=[]):
if len(L)==0:
L.append(0)
L[0]+=i
return L[0]
print(foo4(1),foo4(4),foo4(5))