Consider the following codes
class Bank_acount: def password(self): return 'code:123'
Now consider a few cases when executing the class as below
denny = Bank_acount() denny.password() # function call >> 'code:123'
Next
denny.password # password is function name >> "bound method Bank_acount.password of <__main__.Bank_acount object at 0x00000167820DDCA0>>"
Now if I changed the function name
denny.password = 'code:456' # I changed the function name
I got
denny.password >> 'code:456'
However,
denny.password() >>TypeError: 'str' object is not callable
I am confused
denny.password = 'code:456'
does not make any change toreturn 'code:123'
in the original class, right?- Has the original method
password(self)
been destroyed? - After changing the function name, a new function code:456() pops out?
Thanks!
Advertisement
Answer
Has the original method password(self) been destroyed?
The method still exists, but it has been shadowed by another value only for the denny
instance.
a new function code:456() pops out?
It’s not a function; as the error says, strings are not callable
You can change the code
with a separate attribute, not by a function change
class Bank_acount: def __init__(self, code): self.code = code def password(self): return 'code:' + str(self.code) denny = Bank_acount(123) print(denny.password()) denny.code = 456 print(denny.password())