具有整数仿真的Python类

时间:2009-10-28 16:02:57

标签: python floating-point integer emulation

给出以下示例:

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

    def __int__(self):
        return self.value

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

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

第一个语句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)

如果您再打电话:

f=Foo(some_argument=3)

你得到:

TypeError: 'some_argument' is an invalid keyword argument for this function

使用Python 2.5和2.6进行测试

3 个答案:

答案 0 :(得分:7)

在继承自int的Python 2.4+中起作用:

class MyInt(int):pass
f=MyInt(3)
assert f + 5 == 8

答案 1 :(得分: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

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

>>> 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

有关覆盖new的更多信息,请参阅Unifying types and classes in Python 2.2

答案 2 :(得分:2)

尝试使用最新版本的python。您的代码适用于2.6.1。