python类内置方法的再学习

对于__setitem__和__getitem__方法:其入参看来是固定的(__getitem__(self, item),__setitem__(self, key, value)
),我们并不需要重载实现,另外:类变量看来可以被实例化对象直接使用


class wenwa:
myname = "陈培昌"
myinfo={'name':'陈培昌',"age":22,"favorite":'喜欢练搏击,跳舞'}
def sniff(self):
print("myname:{}".format(self.myname))
def __getitem__(self, item):
print("__getitem__中的打印:{}".format(self.myinfo[item]))
return self.myinfo[item]
def __setitem__(self, key, value):
self.myinfo[key] = value
print("__setitem__中的打印:{}".format(self.myinfo))
kousai = wenwa()
kousai.sniff()
print(kousai['favorite'])
kousai['gift']="苹果手表"
结果:
myname:陈培昌
__getitem__中的打印:喜欢练搏击,跳舞
喜欢练搏击,跳舞
__setitem__中的打印:{'name': '陈培昌', 'age': 22, 'favorite': '喜欢练搏击,跳舞', 'gift': '苹果手表'}
原文地址:https://www.cnblogs.com/saintdingspage/p/10723577.html