0
我有一個python對象,它在概念上允許通過迭代器和getter訪問一個充滿字符串的數組。但是,由於計算數組中每個元素的確切值非常昂貴,我正在考慮爲數組中每個插槽的內容返回一個代理對象,然後在實際需要時即時計算實際值。懶洋洋地提供一個字符串的值
也就是說,我想這樣寫:
bar = foo.get(10) # just returns a proxy
baz = bar # increase proxy reference
l = [baz] # actually increase proxy reference again.
print baz # ooh, actually need the value. Calculate it only the fly.
v = '%s' % bar # I need the value here again
if bar is None: # I need the value here again
print 'x'
if bar: # I need the value here again
print 'x'
for i in bar: # I need the value here again
print i
在C++中,我會嘗試超載對其操作...你知道嗎?
我明白,每一種情況下,我可以重載特定蟒蛇「神奇」的功能(如__str__
爲print baz
),但我不知道:
- 這將實際覆蓋所有可能的usecases(是否有辦法來訪問的變量不使用蟒蛇神奇的功能)
- 還有一個更通用的方法來做到這一點
我很抱歉,但現在很明顯,這個問題還不夠清楚。我編輯過它。 – mathieu
@mathieu:那麼你的問題一點都不清楚,你需要再用Python來玩。自定義類仍然是要走的路,魔術'__str__'掛鉤仍然是提供打印值的方式。因爲它是一個自定義類,所以您仍然可以通過您指定的API訪問實例上的其他數據。 –