给出以下示例:

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 继承,但这次尝试没有成功。

<强>更新

如果要使用 __ init __ ,则继承自 int 会失败:

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进行测试

有帮助吗?

解决方案

您需要覆盖 __ 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 的更多信息,请参阅在Python 2.2中统一类型和类

其他提示

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

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top