Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If I changed the function name in a class, what happen to the function?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

  1. denny.password = 'code:456' does not make any change to return 'code:123' in the original class, right?
  2. Has the original method password(self) been destroyed?
  3. After changing the function name, a new function code:456() pops out?

Thanks!

>Solution :

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading