Sunday, June 27, 2010

Python: Making Objects Callable

Problem Statement: Have you ever wandered if we could make an object callable? Yes, I mean just use the object name as if you were calling function! Intersted?
Here's a simple solution!

Solution:
class Add:
#class for addition
 def __init__(self, num1, num2):
  self.num1 = num1
  self.num2 = num2
  print "Sum of", self.num1, "and", self.num2, "is:"

 def __call__(self):
  return (self.num1 + self.num2)

add = Add(1,2)
print add()

Output:
Sum of 1 and 2 is:
3

Explanation:
In this example, when 'add' is created using add = Add(1,2), def __init__() is called, since the constructor is called while object is getting created.
Because of the attribute __call__, the object becomes callable and hence we could use as add(). when add() is used, def __call__() is called.

Hope it's clear!

No comments: