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
Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.
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.
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 operators? Almost all operators can be overloaded except a few.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With