Using static variables in python classes and functions
This example describes how to use static variables in python classes and functions. 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
?
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 2: Define a class in the 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 3: use anonymous parameters on the stack
?
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 result of the above three sections of code is
?
I hope this article will help you with Python programming.