Python Practice Example 41

Python 100例Python 100 Examples

Question:Imitate the usage of static variables.

Program analysis:None.

Program source code:

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

def varfunc():
    var = 0
    print ('var = %d' % var)
    var += 1
if __name__ == '__main__':
    for i in range(3):
        varfunc()

# Class attributes
# As an attribute of the class
class Static:
    StaticVar = 5
    def varfunc(self):
        self.StaticVar += 1
        print (self.StaticVar)

print (Static.StaticVar)
a = Static()
for i in range(3):
    a.varfunc()

The output of the above example is:

var = 0
var = 0
var = 0
5
6
7
8

Python 100例Python 100 Examples

Other Extensions