Reputation: 77
I'm working on a module and I want the user to be able to use both a(x) (function "a") and a.b(x) (class "a" with function "b"), but Python doesn't seem to let me do that. Is there any way around this?
Upvotes: 0
Views: 59
Reputation: 187
You could do something like this:
class Func:
def __call__(self, x):
return self.b(x)
def b(self, x):
return x ** 2
a = Func()
print(a(2))
print(a.b(2))
Eseentially you overload the call operator to make the object callable, and in this case you just call the desired function b
inside the object.
Voila, and you have achieved what you wanted.
Upvotes: 3