gpt4 book ai didi

具有整数模拟的 Python 类

转载 作者:太空狗 更新时间:2023-10-30 00:28:52 26 4
gpt4 key购买 nike

给出以下示例:

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

def __int__(self):
return self.value

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

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

最佳答案

在从 int 继承的 Python 2.4+ 中:

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

关于具有整数模拟的 Python 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1638229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com