Say I have a basic class in Python 3 which represents some number-like data-type. I want to make it so when I have an instance, x, of this class I can call int(x) and have it call my conversion function to return the integer portion.
I'm sure this is simple, but I can't seem to find out how to do it.
In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading == .
Which operator is overloaded by the __or__() function? Explanation: The function __or__() overloads the bitwise OR operator |.
You could choose to override __builtin__. print , but you'll need to save the original __builtin__. print ; likely mucking with the __builtin__ namespace. If I try using this function in Python 2.7.
The __int__ method is called to implement the built-in int function. The __index__ method implements type conversion to an int when the object is used in a slice expression and the built-in hex , oct , and bin functions.
You override the __int__
magic method as per the following example...
class Test:
def __init__(self, i):
self.i = i
def __int__(self):
return self.i * 2
t = Test(5)
print( int(t) )
# 10
Override the __int__()
method.
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