This article mainly introduces how to use static variables in python classes and functions. The example analyzes three common implementation techniques and has some reference value, for more information about how to use static variables in python classes and functions, see the following example. Share it with you for your reference. The specific analysis is as follows:
It seems impossible to use static variables in python classes and functions (including Lambda methods) [Nothing is impossible,
But there is always a solution. The following describes some non-mainstream methods by implementing a class or function accumulators.
Method 1: Use the _ init _ and _ call _ methods of the class
class foo: def __init__(self, n=0): self.n = n def __call__(self, i): self.n += i return self.na=foo()print a(1)print a(2)print a(3)print a(4)
Method 2: define a class in the function
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).inca=foo2()print a(1)print a(2)print a(3)print a(4)
Method 3: Use Anonymous parameters on the stack
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)
Run in python's official 2.6 environment,
The result of the above three sections of code is
1 3 6 10
I hope this article will help you with Python programming.