二次包装方法 改写__getattr__、__setattr__、__delattr__

可以用类继承的方法,对其他类进行重写。例如:

 1 class List(list):
 2     def show_middle(self):  # 自己定义一个方法
 3         num = int(len(self) / 2)
 4         return self[num]
 5 
 6     def __setattr__(self, key, value):
 7         if type(value) is str:
 8             self.__dict__[key] = value
 9         else:
10             print('你输入的类型错误')
11 
12     def append(self, a):
13         if type(a) is str:
14             # super().append(a)
15             list.append(self, a)  # 必须把self传进去,原因类调用方法必须传入实例本省即self
16         else:
17             print('类型不对')
18 
19 
20 l1 = List('helloworld')
21 l1.append('2')
22 print(l1)
23 print(l1, type(l1))
24 print(l1.show_middle())
25 输出:
26 ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '2']
27 ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '2'] <class '__main__.List'>
原文地址:https://www.cnblogs.com/ch2020/p/12436152.html