Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload all arithmetic operators in Python

Tags:

python

Suppose I build a class that basically represents a number plus some fancy stuff. Instances of that class should behave like numbers in any arithmetic/mathematical operation.

I could overload all numeric operators in that class, but is there no shorter solution?

The class basically looks like:

class MyFancyNumber:
    def __init__(self, num, info):
        self.num = num # the actual number
        self.info = info # some more info, or other data
    def doFancyStuff(self):
        # does something fancy
    def __add__(self, other):
        return self.num + other # same pattern for all numeric functions
like image 417
Michael Avatar asked Feb 27 '17 16:02

Michael


People also ask

Can you overload all operators in Python?

Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.

Which function overloads == in Python?

Python does not support function overloading. When we define multiple functions with the same name, the later one always overrides the prior and thus, in the namespace, there will always be a single entry against each function name.

How are arithmetic operators overloaded?

Overloading Arithmetic Operators as Member Functions This means that a member function to overload a binary arithmetic operator will take one argument rather than the usual two. This also means that the left operand must be an object of our new class in order to overload the operator as a member function of our class.

Can we overload all operator?

Can we overload all operators? Almost all operators can be overloaded except a few.


1 Answers

What about this?

class MyFancyNumber(int):
    def __new__(cls, num, info=None):
        return super(MyFancyNumber, cls).__new__(cls, num)
    def __init__(self, num, info=None):
        self.num = num
        self.info = info
>>> MyFancyNumber(5)
5
>>> MyFancyNumber(5) + 2
7
>>> MyFancyNumber(5) / 4
1
>>> MyFancyNumber(5) * 0.5
2.5
>>> MyFancyNumber(5) - 7
-2
>>> MyFancyNumber(5, 'info').info
'info'

I guess based on the above, you can figure out what you need.

like image 135
Szabolcs Avatar answered Oct 18 '22 05:10

Szabolcs