A. Fattal
A. Fattal

Reputation: 77

Is there a way to name a function and class the same thing in python?

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

Answers (1)

Quizzarex
Quizzarex

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

Related Questions