Exemple pratique Python 41

Python 100例100 exemples Python

Question :Imiter l'utilisation des variables statiques.

Analyse du programme :Aucune.

Code source du programme :

Exemple

#!/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()

# Attributs de classe
# En tant qu'attribut de la classe
class Static:
    StaticVar = 5
    def varfunc(self):
        self.StaticVar += 1
        print (self.StaticVar)

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

La sortie de l'exemple ci-dessus est :

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

Python 100例100 exemples Python

Autres extensions