Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

floating point - Python Class with integer emulation

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Python 2.4+ inheriting from int works:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...