这是python 2.7中的全局变量问题

时间:2015-11-30 18:29:35

标签: python

我正在尝试理解python中的全局变量。 但是我不知道为什么如果我没有声明为全局,_instance_name不会失败 但是当我尝试用_instance_counter做同样的事情时,这就失败了

    #Module global declaration
    _instance_counter = 0
    _instance_name = "Employee module"

    class Employe:
        _internal_counter = 0

        def __init__(self):     
            global _instance_counter#If I comment this line fails.              
            _instance_counter +=1 #count each instance      

           #why if I use _instance_name without global statement doesn't fail
            print("\t**Instance of %s #%i has initialized**"%(_instance_name,_instance_counter))

        def __del__(self):
            print("-The class %s has deleted"%_instance_name)

        def count(self):
            self._internal_counter+=1
            print("count method has %i time(s) called "%self._internal_counter)

        def getTotalInstance(self):                 
            print("\t  %i instance of %s has been created"%(_instance_counter,__name__))


    empl = Employe()
    empl.count()
    empl.count()
    empl.count()


    empl = Employe()
    empl = Employe()
    empl = Employe()

    empl.getTotalInstance()

0 个答案:

没有答案