如何解决无法在 __init__ 函数 Python 中增加全局变量
我试图在 __init__
中增加一个名为“lastIdentify”的全局变量,但我做不到。
class Agent:
lastIdentify = 0
def __init__(self,name,tel,age,gender='ND'):
global lastIdentify
lastIdentify += 1
self._identify = lastIdentify
我也尝试删除 global 语句,但没有任何反应。
我有这个错误: init 中的文件“/.../A/Agent.py”,第 10 行 最后识别 += 1 NameError: name 'lastIdentify' 未定义
谢谢!
解决方法
所以,正如 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,4)
print(f"{agent99.badlastIdentify=},{agent99.lastIdentify=} ")
print(f"{agent007.badlastIdentify=},{agent007.lastIdentify=} " )
print(f"{Agent.badlastIdentify=} {Agent.lastIdentify=} ")
输出:
agent99.badlastIdentify=1,agent99.lastIdentify=2
agent007.badlastIdentify=1,agent007.lastIdentify=2
Agent.badlastIdentify=0 Agent.lastIdentify=2
另见:
What are Python namespaces all about
"Least Astonishment" and the Mutable Default Argument
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。