Using static variables in python classes and functions

Source: Internet
Author: User

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

?

1

2

3

4

1

3

6

10

I hope this article will help you with 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.