gpt4 book ai didi

python - @classmethod 的使用如何导致输出差异?

转载 作者:太空狗 更新时间:2023-10-30 01:11:23 26 4
gpt4 key购买 nike

遇到这个难题时,我正在学习 Python 中的类和对象。下面是相同代码的两种情况,一种没有@classmethod,另一种有@classmethod:

#without @classmethod
>>> class Human:
... name = "Rounak"
... def change_name(self, new_name):
... self.name=new_name
...
>>> Human().change_name("Agarwal")
>>> print(Human().name)
Rounak

#with @classmethod
>>> class Human:
... name = "Rounak"
... @classmethod
... def change_name(self, new_name):
... self.name=new_name
...
>>> Human().change_name("Agarwal")
>>> print(Human().name)
Agarwal

如您所见,当不使用 @classmethod 时,名称不会从 Rounak 更改为 Agarwal。我好像不太明白。

我查看了 Python 文档中 @classmethod 的定义,还查看了 Stack Overflow 上的各种问题,这些问题对 @classmethod 的用法进行了详细解释,但我仍然不明白它是如何导致这种输出差异的。我是 Python 的新手,所以如果我缺少一些基础知识,请告诉我。

最佳答案

使用类方法更改类命名空间 Human.__dict__ 中的名称,这与实例的命名空间 Human().__dict__ 不同。类方法通常使用与 self 不同的变量名作为第一个参数来实现,原因如下:

class Human:  
name = "Rounak"

@classmethod
def change_name(cls, new_name):
cls.name = new_name

请注意,您在打印调用中再次调用了 Human()。每次调用 Human() 时,您都在创建一个新实例,它有自己的命名空间!

关于python - @classmethod 的使用如何导致输出差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51089238/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com