具有整数模拟的 Python 类
给出以下示例:
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 进行测试
Given is the following example:
class Foo(object):
def __init__(self, value=0):
self.value=value
def __int__(self):
return self.value
I want to have a class Foo, which acts as an integer (or float). So I want to do the following things:
f=Foo(3)
print int(f)+5 # is working
print f+5 # TypeError: unsupported operand type(s) for +: 'Foo' and 'int'
The first statement print int(f)+5
is working, cause there are two integers. The second one is failing, because I have to implement __add__
to do this operation with my class.
So to implement the integer behaviour, I have to implement all the integer emulating methods. How could I get around this. I tried to inherit from int
, but this attempt was not successful.
Update
Inheriting from int
fails, if you want to use a __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)
If you then call:
f=Foo(some_argument=3)
you get:
TypeError: 'some_argument' is an invalid keyword argument for this function
Tested with Python 2.5 and 2.6
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Python 2.4+ 中,继承 int 有效:
In Python 2.4+ inheriting from int works:
您需要重写
__new__
,而不是__init__
:现在您的类按预期工作:
有关重写
new
的更多信息可以在 统一 Python 2.2 中的类型和类。You need to override
__new__
, not__init__
:Now your class work as expected:
More information about overriding
new
can be found in Unifying types and classes in Python 2.2.尝试使用最新版本的 python。您的代码适用于 2.6.1。
Try to use an up-to-date version of python. Your code works in 2.6.1.