Reputation: 3539
This should be very simple but I failed to google it: How (if at all) can I overload the parantheses operator in Python? So that this code will make sense:
my_new_object = my_new_class()
x = my_new_object(5)
Upvotes: 2
Views: 230
Reputation: 602345
Define __call__()
on your class:
class MyNewClass(object):
def __call__(self, x):
return x
Upvotes: 8
Reputation: 122719
You should look at the "Callable types" section of this document. In particular, your class could implement __call__
.
Upvotes: 5
Reputation: 38980
You need to define __call__
on your class.
For example
>>> class Multiplier(object):
... def __init__(self, num):
... self.num = num
... def __call__(self, other):
... return self.num*other
...
>>> mul5 = Multiplier(5)
>>> mul5(6)
30
Upvotes: 12