Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overload binary operators to support right application

I’m trying to make a class A that supports both multiplication between two instances of A and scalar multiplication.

I currently have the following implementation for the __mul__ method:

class A:
    def __init__(self, value: float):
        self.value = value

    def __mul__(self, other):
        if type(other) == A:
            return A(self.value * other.value)
        elif type(other) == float:
            return A(other * self.value)
        else:
            raise

This allows to perform multiplication x * y where x is an instance of A and y is an intance of A or float. However if x is a float and y in an A then a TypeError is raised.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a way to overload this case as well? If it matters, I would like the same behaviour regardless of whether the instance of A is the left or right operand.

>Solution :

Add __rmul__:

class A:
    ...
    __rmul__ = __mul__

Attempt This Online!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading