python类和函数中使用静态变量的方法

WBOY
Release: 2016-06-10 15:12:53
Original
1300 people have browsed it

本文实例讲述了python类和函数中使用静态变量的方法。分享给大家供大家参考。具体分析如下:

在python的类和函数(包括λ方法)中使用静态变量似乎是件不可能[Nothing is impossible]的事,
但总有解决的办法,下面通过实现一个类或函数的累加器来介绍一些较为非主流的方法

方法一、通过类的__init__和__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)
print a(2)
print a(3)
print a(4)
Copy after login

方法二、在函数中定义一个类

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)
Copy after login

方法三、使用堆上的匿名参数

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)
Copy after login

在python官方的2.6环境下运行,
上述三段代码得到的结果都是

1 
3 
6 
10 

Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template