class Example(object):
def __init__(self):
self.kk = {}
def __call__(self,id):
self.kk["id"] = id
def __getitem__(self,id):
return self.kk[id]
def __setitem__(self,id,value):
self.kk[id] = value
example = Example()
example["name"] = "oyp" # 相当于 example.__setitem__("name","oyp")
print example["name"] # 相当于 print example.__getitem__("name")
example(123) # 相当于 example.__call__(123)
本文介绍了一个Python类的实现方式,包括如何使用特殊方法如__init__、__call__、__getitem__和__setitem__来定义类的行为。通过实例演示了这些方法的实际应用。
3万+

被折叠的 条评论
为什么被折叠?



