具有整数仿真的Python类

Gün*_*ena 5 python floating-point integer emulation

给出以下示例:

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

    def __int__(self):
        return self.value
Run Code Online (Sandbox Code Playgroud)

我想要一个类Foo,它充当整数(或浮点数).所以我想做以下事情:

f=Foo(3)
print int(f)+5 # is working
print f+5 # TypeError: unsupported operand type(s) for +: 'Foo' and 'int'
Run Code Online (Sandbox Code Playgroud)

第一个语句print int(f)+5正在工作,因为有两个整数.第二个是失败的,因为我必须实现__add__与我的类一起执行此操作.

因此要实现整数行为,我必须实现所有整数模拟方法.我怎么能绕过这个呢.我试图继承int,但这种尝试没有成功.

更新

继承int失败,如果你想使用__init__:

class Foo(int):
    def __init__(self, some_argument=None, value=0):
        self.value=value
        # do some stuff

    def __int__(self):
        return int(self.value)
Run Code Online (Sandbox Code Playgroud)

如果你然后打电话:

f=Foo(some_argument=3)
Run Code Online (Sandbox Code Playgroud)

你得到:

TypeError: 'some_argument' is an invalid keyword argument for this function
Run Code Online (Sandbox Code Playgroud)

使用Python 2.5和2.6进行测试

Hei*_*nen 7

在继承自int的Python 2.4+中:

class MyInt(int):pass
f=MyInt(3)
assert f + 5 == 8
Run Code Online (Sandbox Code Playgroud)


Pär*_*der 5

你需要覆盖__new__,而不是__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
Run Code Online (Sandbox Code Playgroud)

现在你的班级按预期工作:

>>> 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
Run Code Online (Sandbox Code Playgroud)

有关覆盖的更多信息new可以在Python 2.2统一类型和类中找到.