7.10 反射
下述四个函数是专门用来操作类与对象属性的。通过字符串来操作类与对象的属性,这种操作称为反射
class People: country="China" def __init__(self,name): self.name=name def tell(self): print('%s is aaa' %self.name) obj=People('egon')
hasattr:
print(hasattr(People,'country')) #True print('country' in People.__dict__) #True print(hasattr(obj,'name')) #True print(hasattr(obj,'country')) #True print(hasattr(obj,'tell')) #True
getattr:
x=getattr(People,'country',None) print(x) #China f=getattr(obj,'tell',None) print(f) #<bound method People.tell of <__main__.People object at 0x000001E6AA9EACC0>> print(obj.tell) #<bound method People.tell of <__main__.People object at 0x000001E6AA9EACC0>>
setattr:
People.x=111 setattr(People,'x',111) print(People.x) #111 obj.age=18 setattr(obj,"age",18) print(obj.__dict__) #{'name': 'egon', 'age': 18}
delattr:
del People.country delattr(People,"country") print(People.__dict__) del obj.name delattr(obj,"name") print(obj.__dict__) # {'age': 18}
反射的应用:
class Foo: def run(self): while True: cmd=input('cmd>>: ').strip() #用户输入的是字符串 if hasattr(self,cmd): func=getattr(self,cmd) #拿到函数地址 func() def download(self): print('download....') def upload(self): print('upload...') obj=Foo() obj.run()
7.11__str__
方法
__str__( )用于在对象print( )时自动触发 class People: def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex def __str__(self): return '<名字:%s 年龄:%s 性别:%s>' %(self.name,self.age,self.sex) obj=People('egon',18,'male') print(obj) # <名字:egon 年龄:18 性别:male> # print(obj.__str__()) # l=list([1,2,3]) # print(l)
7.12 __del__
方法
__del__( )用于在对象被删除前,自动执行 class MyOpen: def __init__(self,filepath,mode="r",encoding="utf-8"): self.filepath=filepath self.mode=mode self.encoding=encoding self.fobj=open(filepath,mode=mode,encoding=encoding) #申请系统资源 def __del__(self): # 在回收程序空间(对象被删除)前自动触发__del__( ),删除文件空间(系统空间) self.fobj.close() f=MyOpen('aaa.py',mode='r',encoding='utf-8') res=f.fobj.read() print(res)