简体   繁体   中英

__call__ when calling a method inside the class

I'm trying to understand the meaning of __call__ (python3) . Wrote this to differentiate each method __init__ , __call__ , and test method.

#!/usr/bin/python3

class thara(object):

   def __init__(self):
        print("init called")

   def __call__(self):
       print("call called")

   def test(self):
       print("test called")

x=thara()  ### constructor calling here
x()   ## __call__  calling here
x.test() ## test method calling here

my question is when i initiate the x.test() , why it is not calling __call__ ? what I'm thinking is, if i initiate the x.test() will initiate the instance x() , and it should call the __call__ method automatically.But according to my output __call__ will call only when initiate x() .

can someone please explain.

https://docs.python.org/2/reference/datamodel.html#object.__call__

__call__ is called when instance is called like a function. And this is what you do with x() . x.test() is calling method of instance, not instance itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM