python類和函數中使用靜態變數的方法

來源:互聯網
上載者:User

python類和函數中使用靜態變數的方法

   本文執行個體講述了python類和函數中使用靜態變數的方法。分享給大家供大家參考。具體分析如下:

  在python的類和函數(包括λ方法)中使用靜態變數似乎是件不可能[Nothing is impossible]的事,

  但總有解決的辦法,下面通過實現一個類或函數的累加器來介紹一些較為非主流的方法

  方法一、通過類的__init__和__call__方法

  ?

1

2

3

4

5

6

7

8

9

10

11

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)

print a(2)

print a(3)

print a(4)

  方法二、在函數中定義一個類

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

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)

print a(2)

print a(3)

print a(4)

  方法三、使用堆上的匿名參數

  ?

1

2

3

4

5

6

7

8

9

10

def foo3 (i, L=[]):

if len(L)==0:

L.append(0)

L[0]+=i

return L[0]

 

print foo3(1)

print foo3(2)

print foo3(3)

print foo3(4)

  在python官方的2.6環境下運行,

  上述三段代碼得到的結果都是

  ?

1

2

3

4

1

3

6

10

  希望本文所述對大家的Python程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.