How to use static variables in python classes and functions-Python tutorial

Source: Internet
Author: User
This article mainly introduces how to use static variables in python classes and functions. The example analyzes three common implementation techniques and has some reference value, for more information about how to use static variables in python classes and functions, see the following example. 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

class foo:  def __init__(self, n=0):    self.n = n  def __call__(self, i):    self.n += i    return self.na=foo()print a(1)print a(2)print a(3)print a(4)

Method 2: define a class in the function

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).inca=foo2()print a(1)print a(2)print a(3)print a(4)

Method 3: Use Anonymous parameters on the stack

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 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.