user8188120
user8188120

Reputation: 915

Python class default to using one function

I'm trying to make a Python class (call it CLASS) in which there is a main function (call it FUNC) that most users will wish to use.

In this case I would like the user to be able to call the class name without the need to use brackets before the favourite function eg.:

CLASS(B, C) rather than CLASS().FUNC(B, C)

This is purely aesthetic but it means that for users who will use FUNC and not care about the other functions they could explicitly call, they don't need to write the annoying curly brackets.

Here is a simple code example of the kind of class I would create, where the main function (which I've called FUNC for continuity) utilises other functions in the class:

class Example:

    def dummy_operation(self,A):
        return A*2.

    def FUNC(self,B,C):
        A = self.dummy_operation(B)
        result = A + C
        return result

So here, Example takes the place of CLASS for legibility.

One way to do this looks like the use of an if '__main__' statement (see - Python main call within class).

However, as FUNC takes arguments B and C, this will return an error:

if __name__ == '__main__':
    Example().target_function()

Out:

TypeError: target_function() missing 2 required positional arguments: 'B' and 'C'

Is there a way to pass Example(B,C), where in fact it is calling Example().FUNC(B,C) but one can still call Example().dummy_operation(A) if required?

Many thanks in advance!

Upvotes: 1

Views: 1071

Answers (1)

user8188120
user8188120

Reputation: 915

This problem was solved by @snakecharmerb in the comments.

class Example:

    def dummy_operation(self,A):
        return A*2.

    def __call__(self,B,C):
        A = self.dummy_operation(B)
        result = A + C
        return result

Example = Example()
print(Example(1,1))
print(Example.dummy_operation(1))

Out:

3.0
2.0

Upvotes: 1

Related Questions