Python Class with integer emulation

后端 未结 3 941
慢半拍i
慢半拍i 2020-12-18 06:39

Given is the following example:

class Foo(object):
    def __init__(self, value=0):
        self.value=value

    def __int__(self):
        return self.valu         


        
相关标签:
3条回答
  • 2020-12-18 06:47

    Try to use an up-to-date version of python. Your code works in 2.6.1.

    0 讨论(0)
  • 2020-12-18 07:02

    In Python 2.4+ inheriting from int works:

    class MyInt(int):pass
    f=MyInt(3)
    assert f + 5 == 8
    
    0 讨论(0)
  • 2020-12-18 07:12

    You need to override __new__, not __init__:

    class Foo(int):
        def __new__(cls, some_argument=None, value=0):
            i = int.__new__(cls, value)
            i._some_argument = some_argument
            return i
    
        def print_some_argument(self):
            print self._some_argument
    

    Now your class work as expected:

    >>> f = Foo(some_argument="I am a customized int", value=10)
    >>> f
    10
    >>> f + 8
    18
    >>> f * 0.25
    2.5
    >>> f.print_some_argument()
    I am a customized int
    

    More information about overriding new can be found in Unifying types and classes in Python 2.2.

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