带有整数模拟的Python类

7 投票
3 回答
6756 浏览
提问于 2025-04-15 15:27

下面是一个例子:

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 中测试过

3 个回答

2

试着使用最新版本的Python。你的代码在2.6.1版本上可以运行。

7

在Python 2.4及以上版本中,从int这个类型继承是可以的:

class MyInt(int):pass
f=MyInt(3)
assert f + 5 == 8
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 中统一类型和类 找到。

撰写回答