Question
I want to know what is difference between __init__ and __call__ methods? For example :
- class test:
- def __init__(self):
- self.a = 10
- def __call__(self):
- b = 20
The first one __init__ is used to initialize newly created object, and receives arguments used to do that:
Sample code:
- class foo:
- def __init__(self, a, b, c):
- print "foo's __init__ ongoing!"
- self.a=a
- self.b=b
- self.c=c
- def __str__(self):
- return "(a={0};b={1};c={2})".format(self.a, self.b, self.c)
- x = foo(1, 2, 3) # __init__
- print "x={0}".format(x)
The second implements function __call__:
Sample Code:
- class foo:
- def __init__(self, a, b, c):
- print "foo's __init__ ongoing!"
- self.a=a
- self.b=b
- self.c=c
- def __str__(self):
- return "(a={0};b={1};c={2})".format(self.a, self.b, self.c)
- def __call__(self, a, b, c):
- print"Object(a={0};b={1};c={2})".format(a, b, c)
- x = foo(1, 2, 3) # __init__
- print "x={0}".format(x)
- x(3,4,5) # __call__
- x.__call__(4, 5, 6)
Supplement
* Python __new__ 、__init__、 __call__
沒有留言:
張貼留言