[英]Using __getitem__ in operator overloading with python
我如何使用__getitem__
做類似的事情?
class Computers:
def __init__(self, processor, ram, hard_drive):
self.processor = processor
self.ram = ram
self.hard_drive = hard_drive
我想要做的是
C = Computers('2.4 Ghz','4 gb', '500gb')
C['h']
返回500GB
和C['p','r','h']
返回('2.4 Ghz','4 gb','500gb')
是的你可以。 在這兩種情況下,您的__getitem__
方法都將被一個對象調用。 在第一種情況下,將傳遞一個字符串對象,在第二種情況下,將傳遞包含3個字符串的元組 。
處理兩種情況:
def __getitem__(self, item):
attrmap = {'p': 'processor', 'r': 'ram', 'h': 'hard_drive'}
if isinstance(item, str):
return getattr(self, attrmap[item])
# assume a sequence
return tuple(getattr(self, attrmap[i]) for i in item)
演示,包括錯誤處理:
>>> C = Computers('2.4 Ghz','4 gb', '500gb')
>>> C['h']
'500gb'
>>> C['p', 'r', 'h']
('2.4 Ghz', '4 gb', '500gb')
>>> C['f']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in __getitem__
KeyError: 'f'
>>> C['p', 'r', 'f']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in __getitem__
File "<stdin>", line 11, in <genexpr>
KeyError: 'f'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.