[英]How do I return objects from a class without using the __str__ method?
[英]Retrieving data from a class without the str method
我有一個名為Collatz
的類和一個創建該類對象的函數collatz_it
,我正在嘗試使用collatz結構生成一個數字達到1的步數,並使用生成器生成相應的步驟直到100萬
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
正如你所看到的,我使用了一個給定數字的collatz猜想生成了達到1所采取的步驟,並將其添加到具有相應數字的字典中, 但是當我打印出字典值時,它的輸出很尷尬這個:
{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}
任何Python容器的默認表示形式都是使用內容的repr()
輸出,而不是str()
。
解決方案是讓你給collatz.Collatz()
實例一個__repr__
方法(你可以修補它),或者使用dict
的子類,在顯示內容時使用str()
而不是repr()
。
在__repr__
修補猴子可能很簡單:
collatz.Collatz.__repr__ = collatz.Collatz.__str__
當然,如果這是您自己的代碼,只需在類主體中定義一個__repr__
方法。
使用一個繼承自dict
的類,並擁有自己的__repr__
,它__repr__
您的需要。
將所需的值存儲在此行中:
values[count] = i
做點什么
values[count] = i.value
要么
values[count] = str(i)
在最后一種情況下,假設您已為該類編寫了__str__
方法:
class Collatz:
...
def __str__(self):
return str(self.value)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.