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?


class Add:
	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()

Sum of 1 and 2 is:


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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s