Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between a function and a callable object in python? [duplicate]

Tags:

python

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?

like image 946
Chemss-Eddine BenHassine Avatar asked Jan 02 '23 19:01

Chemss-Eddine BenHassine


2 Answers

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

like image 108
iBug Avatar answered Jan 17 '23 07:01

iBug


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.

like image 36
Jean-François Fabre Avatar answered Jan 17 '23 06:01

Jean-François Fabre