Overload int() in Python

2019-01-20 08:39发布

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.

2条回答
在下西门庆
2楼-- · 2019-01-20 09:16

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
查看更多
甜甜的少女心
3楼-- · 2019-01-20 09:22

Override the __int__() method.

查看更多
登录 后发表回答