Methods for using static variables in Python classes and functions

Source: Internet
Author: User

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

?

1 2 3 4 1 3 6 10

I hope this article will help you with your Python programming.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.