[英]confusion because i can't figure out what is changing the attribute of the object of a class in python
Here is my code `这是我的代码`
class Cats:
def __init__(self,name):
self.name=name
#print(self.name,name,"hello")
def change_name(self,new_name):
self.name=new_name
return 0
#print(new_name)
cat1=Cats("lion")
print(cat1)
print(cat1.name)
cat2=cat1.change_name("tiger")
print(cat1.name)
print(cat1)
print(cat2)
** Here is the output with my comments/opinion on the side (pls correct me if i am wrong): ** <__main__.Cats object at 0x7f84272d7640>
error because I tried to print the object cat1 **这是 output ,附上我的评论/意见(如果我错了,请纠正我):**
<__main__.Cats object at 0x7f84272d7640>
错误,因为我试图打印 object cat1
lion
seems fine coz i printed the attribute of the object and since the name given while initialising was lion, it printed lion lion
看起来不错,因为我打印了 object 的属性,并且由于初始化时给出的名称是 lion,它打印了 lion
tiger
THIS IS WHAT I DON'T UNDERSTAND. tiger
这就是我不明白的。 why is this output tiger and not lion.为什么这个 output 是老虎而不是狮子。 what exactly caused this change?
究竟是什么导致了这种变化? Bcoz when I do <<cat2=cat1.change_name("tiger"), it should just assign the value 0 to cat2 but why did it change the value in cat1?
Bcoz 当我执行 <<cat2=cat1.change_name("tiger") 时,它应该只将值 0 分配给 cat2,但为什么它更改了 cat1 中的值?
<__main__.Cats object at 0x7f84272d7640>
error bcoz i tried to print a class <__main__.Cats object at 0x7f84272d7640>
错误 bcoz 我试图打印 class
0
seems fine coz chane_name function returns 0 which is assigned to cat2 0
似乎很好因为 chane_name function 返回分配给 cat2 的 0
I was expecting the value of cat1.name to remain the same (it should have remained lion and not changed to tiger)我期望 cat1.name 的值保持不变(它应该保持为 lion 而不是更改为 tiger)
When you call cat1.change_name("tiger")
, a few things happen:当您调用
cat1.change_name("tiger")
时,会发生一些事情:
self
is bound to the same object as cat1
.self
绑定到与 cat1 相同的cat1
。cat1.name
is changed from "lion"
to "tiger"
cat1.name
从"lion"
更改为"tiger"
change_name
returns 0
, not a new instance of Cats
. change_name
返回0
,而不是Cats
的新实例。 After this call, cat1.name
evaluates to "tiger"
, not "lion"
, because the value has changed.此次调用后,
cat1.name
计算结果为"tiger"
,而不是"lion"
,因为值已更改。
print(cat1)
outputs your "error message" because print
implicitly calls str
on its argument, and since Cats
does not define __str__
, object.__str__
is used instead, and that produces the string you see. print(cat1)
输出您的“错误消息”,因为print
在其参数上隐式调用str
,并且由于Cats
未定义__str__
,因此使用object.__str__
,并生成您看到的字符串。
print(cat2)
output 0
because that's the value that was assigned to cat2
as the return value of cat1.change_name("tiger")
. print(cat2)
output 0
因为这是作为cat1.change_name("tiger")
的返回值分配给cat2
的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.