-2

I'm trying to increment a global variable called "lastIdentify" in the __init__ and I can not do it.

class Agent:

   lastIdentify = 0

   def __init__(self,name,tel,age,gender='ND'):
      global lastIdentify
      lastIdentify += 1
      self._identify = lastIdentify

I also tried deleting the global statement and nothing happened.

I have this error: File "/.../A/Agent.py", line 10, in init lastIdentify += 1 NameError: name 'lastIdentify' is not defined

Thank you!

ladytoky0
  • 588
  • 6
  • 16

1 Answers1

1

So, as Barmar thought, you had a class variable in mind.

The tricky part here is: Python has mutable data (lists, dictionaries, sets...) and immutable data (ints, floats, strings...).

When you modify a class level immutable variable you copy and bind it to the instance's scope/namespace. That is what is happening on badlastIdentify.

On the other hand, if you start mutating a class-scoped mutable attribute, for example a list, you'd find that you are modifying the class-level variable, i.e. your list would get bigger all around, even if that is not what you wanted.

And, in your original code, global lastIdentify was something yet again: it didn't previously exist, could not be incremented, and had no relation to your class. Generally speaking, global as a keyword in Python is a bit of a code smell, it's usually better handled differently. And, no, I am not a person who gets all religious about globals and singletons being bad, just specifically when global is being used.

class Agent:

   lastIdentify = 0
   badlastIdentify = 0

   def __init__(self,name,tel,age,gender='ND'):

      # you are operating on the class namespace, 
      #not on an instance-specific variable
      self.__class__.lastIdentify += 1

      #this doesnt "mutate" the class-variable
      #it binds a new copy of it, +1, to this instance
      self.badlastIdentify += 1

agent99 = Agent(1,2,3,4)
agent007 = Agent(1,2,3,4)

print(f"{agent99.badlastIdentify=} , {agent99.lastIdentify=} ")
print(f"{agent007.badlastIdentify=} , {agent007.lastIdentify=} " )
print(f"{Agent.badlastIdentify=}  {Agent.lastIdentify=} ")


output:

agent99.badlastIdentify=1 , agent99.lastIdentify=2
agent007.badlastIdentify=1 , agent007.lastIdentify=2
Agent.badlastIdentify=0  Agent.lastIdentify=2

see also:

What are Python namespaces all about
"Least Astonishment" and the Mutable Default Argument

JL Peyret
  • 10,917
  • 2
  • 54
  • 73