class Adder:
def __call__(self, x, y):
return x + y
add1 = Adder()
def add2(x, y):
return x + y
What's the difference between add1
and add2
other than the type?
In your super-simple example. there's no practical difference, since functions are also callable objects.
However, a callable object is an object of a class that you write, so you may write this code:
class Counter:
def __init__(self, value = 0):
self.n = 0
def __call__(self):
self.n += 1
return self.n
def __repr__(self):
return str(self.n)
redWins = Counter()
blueWins = Counter()
if foo():
redWins()
else:
blueWins()
print("Red has won {} times.\nBlue has won {} times."
.format(redWins, blueWins))
And you'll find it hard to implement such a class using only functions. Even if you try to do it with global variables, you can't have separate instances of one single global variable.
See more: Functions, Callable Objects, and how both are created in Python
In your example, there's no functional difference but since add1
is an object, you can store information in the members:
class Adder:
def __init__(self):
self.__memory = 0
def __call__(self, x, y):
self.__memory += x
return x+y+self.__memory
add1 = Adder()
print(add1(10,10))
print(add1(10,10))
you get 30
then 40
. You can do that with a function, but then you need a global variable, and using global variables is really asking for trouble.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With