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.

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.