2013-07-03 35 views
1

我擁有一個名爲Collatz的類和一個函數collatz_it,它創建該類的一個對象,我試圖使用collatz conjucture生成一個數字的步驟數達到1,直到百萬它們相應的步驟,使用一臺發電機從沒有str方法的類中檢索數據

import collatz 
values = {} 
count = 0 
#collatz.collatz_it(n) 

def gen(): 
    n = 0 
    x = 0 
    while True: 
     yield x 
     n += 1 
     x = collatz.collatz_it(n) 

for i in gen(): 
    count += 1 
    values[count] = i 
    print values 
    if count == 1000000: 
     break 

正如你所看到的,我產生的採取它步驟的量使用給定數量的考拉茲猜想達到100,並與相應的添加到字典編號當我打印出字典值時,它的輸出很笨拙,像這樣:

{1: 0} 
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>} 
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>} 
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>, 4: <collatz.Collatz instance at 0x01DCDFA8>} 
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>, 4: <collatz.Collatz instance at 0x01DCDFA8>, 5: <collatz.Collatz instance at 0x01DCDEB8>} 
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>, 4: <collatz.Collatz instance at 0x01DCDFA8>, 5: <collatz.Collatz instance at 0x01DCDEB8>, 6: <collatz.Collatz instance at 0x01DCDE90>} 
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>, 4: <collatz.Collatz instance at 0x01DCDFA8>, 5: <collatz.Collatz instance at 0x01DCDEB8>, 6: <collatz.Collatz instance at 0x01DCDE90>, 7: <collatz.Collatz instance at 0x01DE8940>} 

如果我打印的print i代替print values我得到所需的輸出,這基本上是因爲print聲明觸發類的__str__方法

是不是有什麼辦法可以增加的實際步驟在不輸入<collatz.Collatz instance at 0x01DCDFA8>字典中,是否有任何形式的檢索數據,從__str__方法的方法,使我的字典裏看起來是這樣的:

{1: 0} 
{1: 0, 2: 1} 
{1: 0, 2: 1, 3: 7} 
+0

爲什麼不能使用'__str__'?或者'__repr__'呢? – 2rs2ts

+0

任何Python容器的缺省表示是使用內容的'repr()'輸出,而不是'str()'。 –

回答

3

任何Python容器的缺省表示是使用內容的repr()輸出,而不是str()

的解決方案將是爲你或者(在可以猴補丁)得到collatz.Collatz()實例__repr__方法,或使用的dict一個子類顯示內容時使用str()代替repr()

猴修補的__repr__可能是那樣簡單:

collatz.Collatz.__repr__ = collatz.Collatz.__str__ 

當然,如果這是你自己的代碼,只是定義類體本身__repr__方法。

+0

...或者更簡單:'collat​​z.Collat​​z。__repr__ = lambda x:str(x)' – Aya

+0

或'X .__ repr__ = X .__ str__';)但是猴子修補他們自己的類有什麼意義? – georg

+0

@ thg435:我認爲這不是他們自己的。 –

0

使用繼承自dict的類,並擁有自己的__repr__,它可以做你想做的事。

0

存儲要在這條線的值:

values[count] = i

這樣做

values[count] = i.value

values[count] = str(i)

在最後一種情況下,假定您已經編寫了該類的__str__方法:

class Collatz: 
... 
def __str__(self): 
    return str(self.value) 
相關問題