Skip to content
Advertisement

Wrapping a class instance by its own method

Suppose we have a python class like below:

JavaScript

Both f and g serves as functions on the class instance in some mathematical notation. For example, I desire to run f(g(value)) in the notation. In the above class definition, the way to achieve it is by running test1.g().f(). Although there is nothing wrong with the code, I just don’t like the fact that the order has changed, and it makes the line not that readable from a mathematics perspective.

I wonder if I could run the line like f(g(value)) with some custom magic or dunder method, but could not find one.

I understand that the way to achieve it is simply taking f and g out from the class like:

JavaScript

However, I have some other similar classes that also have the same function/method names (f, g). So, if I run

JavaScript

there will be obvious conflicts. I understand that I could do things like

JavaScript

but, not that pleasant with this.

Is there any custom package like functools that provide any ways? What I am expecting is something like

JavaScript

Thank you in advance.

Advertisement

Answer

Your Test1 and Test2 classes have the same interface. We can model that

JavaScript

Now we know the interface and can define the free function f and g in terms of that interface:

JavaScript

Now the free functions f and g are compatible with every class that implements the protocol:

JavaScript

Actually, you don’t need the protocol at all. If you don’t care about mypy, remove all type hints and the protocol.

So here is the “short” form without type hints:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement