Overload int() in Python

前端 未结 2 1923
遥遥无期
遥遥无期 2020-12-07 00:50

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 i

相关标签:
2条回答
  • 2020-12-07 01:28

    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
    
    0 讨论(0)
  • 2020-12-07 01:35

    Override the __int__() method.

    0 讨论(0)
提交回复
热议问题