The examples in this article describe methods for using static variables in Python classes and functions. Share to everyone for your reference. The specific analysis is as follows:
The use of static variables in Python classes and functions (including the lambda method) seems to be something that is not possible [is impossible].
But there is always a solution, the following is to implement a class or function of the accumulator to introduce some of the more Non-mainstream method
Methods one, through the __init__ and __call__ methods of class
?
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) |
Method Two, define a class in a function
?
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) |
Method three, using anonymous parameters on the heap
?
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 ) |
Run in Python's official 2.6 environment,
The results of all three of these codes are
?
I hope this article will help you with your Python programming.