__call__ in Python, the function is actually an object:>>> f = abs>>> f.__name__ ' abs ' >>> f (-123) 123 because F can be called, so, F is called a callable object. All functions are callable objects. An instance of a class can also become a callable object, just to implement a special Method __call__ (). We turn the person class into a callable object: Class Person (object): def __init__ (self, Name, gender): self.name = name self.gender = Gender def __call__ (self, Friend): " print ' My name is%s ... '% self.name print ' My Friend is%s ... '% friend now On the person instance that can be called directly:>>> p = person (' bob ', ' Male ') >>> p (' Tim ') My name is Bob ... My Friend is Tim ... See P (' Tim ') you can't tell if P is a function or a class instance, so in Python, the function is also an object, and the difference between objects and functions is not significant. Task to improve the previously defined Fibonacci sequence: Class Fib (object): ??? Please add a __call__ method to make the call simpler:>>> F = Fib () >>> print F (10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
The instance object can be represented in the form of a similar function, further blurring the concept between the function and the object
Class Fib (object): def __init__ (self): pass def __call__ (self,num): A, B = 0,1; Self.l=[] for i in range (num): self.l.append (a) a,b= b,a+b return SELF.L def __str__ (self): return str (SELF.L) __rept__=__str__ f = Fib () print F (10)
Python special function __call__ ()