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
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.
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)