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
lion
seems fine coz i printed the attribute of the object and since the name given while initialising was lion, it printed lion
tiger
THIS IS WHAT I DON'T UNDERSTAND. why is this output tiger and not lion. 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 ?
<__main__.Cats object at 0x7f84272d7640>
error bcoz i tried to print a class
0
seems fine coz chane_name function returns 0 which is assigned to cat2
I was expecting the value of cat1.name to remain the same (it should have remained lion and not changed to tiger)
CodePudding user response:
When you call cat1.change_name("tiger")
, a few things happen:
- The name
self
is bound to the same object ascat1
. - As a result,
cat1.name
is changed from"lion"
to"tiger"
change_name
returns0
, not a new instance ofCats
.
After this call, cat1.name
evaluates to "tiger"
, not "lion"
, because the value has changed.
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(cat2)
output 0
because that's the value that was assigned to cat2
as the return value of cat1.change_name("tiger")
.