Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload int() in Python

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.

like image 936
LordLing Avatar asked Jul 20 '12 08:07

LordLing


People also ask

How do you overload in Python?

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 in Python?

Which operator is overloaded by the __or__() function? Explanation: The function __or__() overloads the bitwise OR operator |.

Which function overloads the print () statement in Python?

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.

What is __ INT __ in Python?

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.


2 Answers

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
like image 74
Jon Clements Avatar answered Sep 29 '22 01:09

Jon Clements


Override the __int__() method.

like image 29
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 23:09

Ignacio Vazquez-Abrams