Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Exercise Example 41

Python Exercise Example 41

Python 100 Examples Python 100 Examples

**Question:** Imitate the use of static variables.

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

Use it 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 Examples Python 100 Examples