python12——包装标准类

#包装 class List_feng(list): def show_midle(self): mid_index = int(len(self)/2) return self[mid_index]l1 = List_feng('helloworld') print(l1) print(l1.show_midle()) #授权 class Open: def __init__(self,filename,mode='r',encoding='utf-8'): self.file = open(filename,mode,encoding=encoding) # self.mode = mode # self.encoding = encoding #此时无法进行写入 def write(self): pass def __getattr__(self, item): print(item,type(item)) return getattr(self.file,item) f1 = Open('a.txt','w') print(f1.file) print(f1.read)

class Feng: pass f1 = Feng() #是否被实例 print(isinstance(f1,Feng))class Sub_feng(Feng): def __getattr__(self, item): print('执行了1111111') #都会触发 def __getattribute__(self, item): print('执行了22222') raise AttributeError('抛出异常了')print(issubclass(Sub_feng,Feng))

item系列
class Feng: def __getitem__(self, item): print('getitem') return self.__dict__[item] def __setitem__(self, key, value): print('setitem') self.__dict__[key]=value def __delitem__(self, key): print('delitem') self.__dict__.pop(key) f1 = Feng() #f1.name = 'fengfeng' f1['name']='fengfeng' print(f1.__dict__) print(f1['name']) del f1['name'] print(f1.__dict__)

【python12——包装标准类】Str 和 Repr
l = list('hello') print(l)class Feng: def __str__(self): return '自定义显示方式' def __repr__(self): return 'repr__________' f1 = Feng() print(f1)

    推荐阅读