如果在python的类中定义了__getitem__()的魔法方法,实例对象可以通过键值来取值。
class Test:
def __init__(self, num, flower):
self.num = num
self.flower = flower
self.dict = dict()
self.getDict()
def getDict(self):
for n,f in zip(self.num,self.flower):
self.dict[n] = f
def __getitem__(self, key):
return self.dict[key]
num = [1,2,3,4,5]
flower = ['琼花','玉茗','叠罗金','蓬莱紫','玉玲珑']
test = Test(num,flower)
print(test[4])
他的输出结果:
蓬莱紫