Python对象内置方法
1. __getattr__
class Foo: def __init__(self): self.x=123 """ item 为调用不存在的属性 该方法在对象调用不存在属性的时候触发执行 """ def __getattr__(self, item): print('__getattr__ ') print(item) f=Foo() f.x1
2. __delattr__
class Foo: def __init__(self): self.x=123 """ 1. item 为删除的属性 2. 该方法在对象删除属性时候触发执行
3. 重写了该方法后就必须实现它,否则无法删除属性
注意: 不能使用 del item 来进行删除,否则会导致递归 """ def __delattr__(self, item): print('__delattr__ ') del self.__dict__[item] f=Foo() del f.x
3. __setattr__
class Foo: def __init__(self): self.x=123 """ 1.key 为需要设置对象的属性 2.value 为需要设置对象属性的值 3.该方法在对象设置属性的时候触发执行
4.重写了该方法后就必须实现它,否则无法添加属性 注意: 不能使用 self.key=value来进行设置,否则会导致递归 """ def __setattr__(self, key, value): print('__setattr__') self.__dict__[key]=value f=Foo() print(f.x) f.y=456 print(f.y)
========================================================
getitem, setitem,delitem 和 getattr,setattr,delattr差不多,区别只是在于这3个内置方法用于字典的形式操作属性。
class Foo: def __init__(self): pass def __getitem__(self, item): print('__getitem__') return self.__dict__[item] def __setitem__(self, key, value): self.__dict__[key]=value print('__setitem__') def __delitem__(self, key): print('__delitem__') del self.__dict__[key] f=Foo() f['name']='liang' f['name'] del f['name']
=================================================================================================
对象内置 format 方法
class Foo: def __init__(self,year,month,day): self.year=year self.month=month self.day=day def __format__(self, format_spec): if format_spec =='yyyy-mm-dd': return '%s-%s-%s'%(self.year,self.month,self.day) elif format_spec =='yyyy/mm/dd': return '%s/%s/%s' % (self.year, self.month, self.day) f=Foo('2020','11','26') """ 使用 format内置方法,会自动触发 __format__方法, """ date=format(f,'yyyy-mm-dd') print(date) date=format(f,'yyyy/mm/dd') print(date)
#======================================================================
getattr 和 getattribute 的区别使用
class Foo: def __init__(self,x): self.x=x """ 1. __getattr__ 是当对象调用不存在的实例属性时候触发该函数; 2. 如果让该函数触发,必须满足抛出异常机制 """ def __getattr__(self, item): print('%s 不存在'%item) print('__getattr__') """ 1.__getattribute__ 是当对象调用存在或不存在的实例属性的时候触发该函数 2. 如果调用不存在的属性的时候,需要raise 异常机制,否则 __getattr__函数无法触发 3. 如若__getattr__函数触发执行,则本函数也执行 """ def __getattribute__(self, item): print(item) print('__getattribute__') raise AttributeError obj=Foo(10) obj.x1
#======================================================================
内置 getattr 方法使用
class MyFile: def __init__(self,file): self.file=open(file,'r',encoding='utf-8') def __getattr__(self, item): return getattr(self.file,item) f=MyFile('config.txt') data=f.read() print(data)