2009-10-28 71 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