2009-10-28 67 views
5

是下面的例子:Python类具有给定整数仿真

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

    def __int__(self): 
     return self.value 

我希望有一类,其作为一个整数(或浮动)。所以,我想要做以下的事情:

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) 

你:

测试与Python 2.5和2.6

+1

我不明白你的问题。你怎么能绕过你必须做的一件事,以便不做你必须做的一件事? Fishslap! – 2009-10-28 16:05:55

+0

我想要一个类似整数的类。真正的整数实现总是相同的,所以为什么每次使用它都要实现它。当你使用'+' - 运算符时,__add__方法是有意义的。 – 2009-10-28 16:11:51

回答

5

你需要重写__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信息可以在Unifying types and classes in Python 2.2找到。

7

在Python 2.4及以上的从int继承工作:

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

我在为构造函数使用命名参数时出现了问题(__init__)。当我调用f = MyInt(other_argument = True)时,它失败(TypeError:'other_argument'是此函数的无效关键字参数) – 2009-10-28 16:26:47

+1

@GüntherJehle:请将此添加到您的问题。这个评论不符合你的问题,在这个问题的背景下没有太多意义。请更新问题以包含所有事实。 – 2009-10-28 17:08:56

+0

添加了从int继承的结果 – 2009-10-28 17:44:32

2

尝试使用Python的先进的最新版本。你的代码在2.6.1中工作。

+0

我会试试这个 – 2009-10-28 16:27:28

+0

我的python版本目前是2.5.1 – 2009-10-28 16:28:05

+0

等等,你为什么要从'object'继承? 如果您从'int'继承,则代码有效。 – jdb 2009-10-28 17:00:05