Is it possible to make an object callable by implementing either call
or apply
on it, or in some other way? E.g.:
var obj = {}; obj.call = function (context, arg1, arg2, ...) { ... }; ... obj (a, b);
The “calling” is achieved by placing a pair of parentheses following the function name, and some people refer to the parentheses as the call operator. Without the parentheses, Python interpreter will just generate a prompt about the function as an object itself — the function doesn't get called.
To make a class instance callable, all you need to do is implement a __call__ method. Then, to call the __call__ method, you just do: instance(arg1,arg2,...) -- in other words, you call the instance the same way you would call a function.
A callable object, in computer programming, is any object that can be called like a function.
Python's functions are callable objects So, every function in Python is a callable, meaning it's an object that you're able to call.
No, but you can add properties onto a function, e.g.
function foo(){} foo.myProperty = "whatever";
EDIT: to "make" an object callable, you'll still have to do the above, but it might look something like:
// Augments func with object's properties function makeCallable(object, func){ for(var prop in object){ if(object.hasOwnProperty(prop)){ func[prop] = object[prop]; } } }
And then you'd just use the "func" function instead of the object. Really all this method does is copy properties between two objects, but...it might help you.
ES6
has better solution for this now. If you create your objects in a different way (using class
, extend
ing 'Function' type), you can have a callable instance of it.
See also: How to extend Function with ES6 classes?
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