Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to define a class that behaves like a function? [duplicate]

I would like to define in python a class that behaves like a function with additional attributes. In particular, it should be seamlessly applied to a variable.

Let’s try to explain with a mathematical example. Say I am very much into sinusoïdal functions, but also interested by their frequency. A function x -> sin(omega x) has the attribute frequency, namely the value of omega. It can also be applied to a float x.

I can write:

from numpy import sin, pi

class SinFunc:
    def __init__(self, omega):
        self.frequency = omega

    def apply_to(self, x):
        return sin(self.frequency * x)

I could then play with a sinusoïdal function:

MySinFunc = SinFunc(3)
print(MySinFunc.frequency)
print(MySinFunc.apply_to(pi)) 
# output
# 3
# 0 (almost!)

But what I would like is to be able to write directly MySinFunc(pi), with the attribute frequency still defined.

How to achieve that? Thanks!

like image 707
AGuilloux Avatar asked Mar 09 '26 10:03

AGuilloux


1 Answers

To make an object callable, you need to add a __call__ class method that will handle the call.

Rename your apply_to function to __call__ and it will work.

like image 197
gshpychka Avatar answered Mar 12 '26 20:03

gshpychka