程式扎記: [ Python 常見問題 ] what is difference between __init__ and __call__?

標籤

2015年2月9日 星期一

[ Python 常見問題 ] what is difference between __init__ and __call__?

Source From Here 
Question 
I want to know what is difference between __init__ and __call__ methods? For example : 
  1. class test:  
  2.   def __init__(self):  
  3.     self.a = 10  
  4.   
  5.   def __call__(self):   
  6.     b = 20  
Answer: 
The first one __init__ is used to initialize newly created object, and receives arguments used to do that: 
Called after the instance has been created (by __new__()), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an __init__() method, the derived class’s __init__() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: BaseClass.__init__(self, [args...]).

Sample code: 
  1. class foo:  
  2.     def __init__(self, a, b, c):  
  3.         print "foo's __init__ ongoing!"  
  4.         self.a=a  
  5.         self.b=b  
  6.         self.c=c  
  7.     def __str__(self):  
  8.         return "(a={0};b={1};c={2})".format(self.a, self.b, self.c)  
  9.   
  10. x = foo(123) # __init__  
  11. print "x={0}".format(x)  
Execution result: 
foo's __init__ ongoing!
x=(a=1;b=2;c=3)

The second implements function __call__
Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).

Sample Code: 
  1. class foo:  
  2.     def __init__(self, a, b, c):  
  3.         print "foo's __init__ ongoing!"  
  4.         self.a=a  
  5.         self.b=b  
  6.         self.c=c  
  7.           
  8.     def __str__(self):  
  9.         return "(a={0};b={1};c={2})".format(self.a, self.b, self.c)  
  10.       
  11.     def __call__(self, a, b, c):  
  12.         print"Object(a={0};b={1};c={2})".format(a, b, c)  
  13.   
  14. x = foo(123) # __init__  
  15. print "x={0}".format(x)  
  16. x(3,4,5) # __call__  
  17. x.__call__(456)  
Execution result: 
foo's __init__ ongoing!
x=(a=1;b=2;c=3)
Object(a=3;b=4;c=5)
Object(a=4;b=5;c=6)

Supplement 
Python __new__ 、__init__、 __call__

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!