0

I'm trying to understand global variables in python. But I don't know why _instance_name doesn't fail if I don't declared as global but when I try to do the same thing with _instance_counter this fail

    #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()
lord.garbage
  • 5,884
  • 5
  • 36
  • 55
MrAlex6204
  • 167
  • 7
  • `_instance_counter +=1` is not defined in current scope (`__init__`) – Valijon Nov 30 '15 at 18:32
  • @Valijon. Yes, but `print(...%(_instance_name...))` is defined in the current scope. Why? – Mad Physicist Nov 30 '15 at 18:34
  • @mad-physicist That's what I'm trying to understand, even if you change the data type to 1.5 or some thing else it works without global statement – MrAlex6204 Nov 30 '15 at 18:39
  • 1
    the scoping issue is that a global can be referenced for use without declaring it in the local scope but cannot be modified when you went to change the variable it was not defined locally (or as global in local function) so it failed – gkusner Nov 30 '15 at 18:41

0 Answers0