Consider the following codes
JavaScript
x
4
1
class Bank_acount:
2
def password(self):
3
return 'code:123'
4
Now consider a few cases when executing the class as below
JavaScript
1
5
1
denny = Bank_acount()
2
denny.password() # function call
3
4
>> 'code:123'
5
Next
JavaScript
1
4
1
denny.password # password is function name
2
3
>> "bound method Bank_acount.password of <__main__.Bank_acount object at 0x00000167820DDCA0>>"
4
Now if I changed the function name
JavaScript
1
2
1
denny.password = 'code:456' # I changed the function name
2
I got
JavaScript
1
4
1
denny.password
2
3
>> 'code:456'
4
However,
JavaScript
1
4
1
denny.password()
2
3
>>TypeError: 'str' object is not callable
4
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
JavaScript
1
11
11
1
class Bank_acount:
2
def __init__(self, code):
3
self.code = code
4
def password(self):
5
return 'code:' + str(self.code)
6
7
denny = Bank_acount(123)
8
print(denny.password())
9
denny.code = 456
10
print(denny.password())
11