Python __call__ equivalent in Julia

In python, one can use an instance as a function by defining __call__ as following code. I want to do the similar thing in Julia by using a struct instead of a class. Could anyone tell me how to do this?

class Mul:
    def __init__(self, a):
        self.a = a
    def __call__(self, x):
        return self.a * x

if __name__=='__main__':
    m = Mul(2)
    m(2) # equals to 4

Like so:

julia> struct A

julia> (a::A)(x) = a.a*x

julia> A(2)(2)

PS: but don’t do OO programming in Julia :wink:


I know many don’t enjoy semantics nearly so much as I do, but multiple dispatch is considered to be a form of OO programming by many. It’s just not class-based object orientation which seems to have taken over as the one and only form of OO in many people’s minds.

1 Like

Here’s a non-OO alternative:

make_mul(a) = x-> a*x

mul = make_mul(2)


I disagree that this is less OO than what @mauro3 showed (regardless of what the term OO actually means). The closure you show in your code is implemented as a struct storing a. The only real difference between the two examples is that yours is one line shorter but produces intermediate outputs which might be less legible and shouldn’t be dispatched on.

julia> dump(mul)
#13 (function of type var"#13#14"{Int64})
  a: Int64 2

edited to make the tone seem less aggressive (did not mean to be aggressive)

Fair enough. I was just showing an alternative, if it is actually OO I’m not going to argue.