Python 實現累加計數的幾種方法



#要實現累加,關鍵在於數據存在哪兒,怎么使每次累加的都是同一個變量 行為像靜態變量

#前兩種都是數據存到類的成員變量,
# 類利用__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))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM