Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法在_init__函数中递增全局变量_Python_Variables_Global_Init - Fatal编程技术网

Python 无法在_init__函数中递增全局变量

Python 无法在_init__函数中递增全局变量,python,variables,global,init,Python,Variables,Global,Init,我试图在\uuu init\uuuu中增加一个名为“lastIdentify”的全局变量,但我做不到 class Agent: lastIdentify = 0 def __init__(self,name,tel,age,gender='ND'): global lastIdentify lastIdentify += 1 self._identify = lastIdentify 我还试图删除全局语句,但什么也没发生 我有一个错误: 文件

我试图在
\uuu init\uuuu
中增加一个名为“lastIdentify”的全局变量,但我做不到

class Agent:

   lastIdentify = 0

   def __init__(self,name,tel,age,gender='ND'):
      global lastIdentify
      lastIdentify += 1
      self._identify = lastIdentify
我还试图删除全局语句,但什么也没发生

我有一个错误: 文件“/…/A/Agent.py”,第10行,在init lastIdentify+=1 NameError:未定义名称“LastIdentity”


谢谢大家!

所以,正如Barmar所想,您心里有一个类变量

这里比较棘手的部分是:Python有可变数据(列表、字典、集合…)和不可变数据(整数、浮点、字符串…)

修改类级别的不可变变量时,需要将其复制并绑定到实例的作用域/命名空间。这就是
badlastIdentify
上发生的情况

另一方面,如果你开始改变一个类范围的可变属性,例如一个列表,你会发现你正在修改类级别的变量,也就是说,你的列表会变得更大,即使这不是你想要的

而且,在您的原始代码中,
global lastIdentify
又是一个东西:它以前不存在,不能递增,并且与您的类没有关系。一般来说,
global
作为Python中的一个关键字有点代码味道,通常最好以不同的方式处理。而且,不,我不是一个对全球人和单身人士的坏习惯信以为真的人,尤其是在使用
global
的时候

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=} ")


输出: 另见:



为什么你不能这样做?没有理由不这样做。请发布一个。你确定这是一个全局变量,不是类变量吗?在你提供的代码中没有类的符号。请给出一个简单的例子来重现这个问题。我编辑了我的文章,它是在python类中定义的。
agent99.badlastIdentify=1 , agent99.lastIdentify=2
agent007.badlastIdentify=1 , agent007.lastIdentify=2
Agent.badlastIdentify=0  Agent.lastIdentify=2