我正在尝试简化代码,我认为我可以重载 getitem ,就像列表和字典一样。我不应该这样做吗?
class Book:
def __init__(self):
self.page_id = []
self.page = []
def __getitem__(self, ref):
if type(ref) is int:
return self.page[ref]
elif type(ref) is str:
page_index = self.page_id.index(ref)
return self.page[page_index]
这样我可以支持这样的事情
book = Book()
page_1 = book[5]
page_8 = book['id_for_page_8']
答案 0 :(得分:1)
你可以通过简单的尝试/除
来更加pythonicclass Book:
def __init__(self):
self.page_id = []
self.page = []
def __getitem__(self, ref):
try:
return self.page[ref] # assume it's an int
except TypeError:
return self.page[self.page_id.index(ref)] # assume it's a string if not an int
作为一般提示,使用isinstance是type的更好选择,因为isinstance了解继承。