python是动态语言,而反射(reflection)机制被视为动态语言的关键。
反射机制指的是在程序的运行状态中
对于任意一个类,都可以知道这个类的所有属性和方法;
对于任意一个对象,都能够调用他的任意方法和属性。
这种动态获取程序信息以及动态调用对象的功能称为反射机制。
指的是在程序运行过程中可以"动态(不见棺材不掉泪)"获取对象的信息
以下代码,当直接传入int类型时,因其无属性x,故报错。而反射,则可以动态获取其属性,并判断
def func(obj): if ‘x‘ not in obj.__dict__: return obj.x func(10) # AttributeError: ‘int‘ object has no attribute ‘__dict__‘
1、先通过多dir:查看出某一个对象下可以.出哪些属性来
print(dir(obj))
2、可以通过字符串反射到真正的属性上,得到属性值
print(obj.__dict__[dir(obj)[-2]])
class People: def __init__(self,name,age): self.name=name self.age=age def say(self): print(‘<%s:%s>‘ %(self.name,self.age)) obj=People(‘辣白菜同学‘,18)
四个内置函数的使用:通过字符串来操作属性值
# 1、hasattr() print(hasattr(obj,‘name‘)) # True print(hasattr(obj,‘x‘)) # False # 2、getattr() print(getattr(obj,‘name‘)) # 辣白菜同学 print(getattr(obj, ‘x‘)) # AttributeError: ‘People‘ object has no attribute ‘x‘ print(getattr(obj,‘x‘,None)) # None # 3、setattr() setattr(obj,‘name‘,‘EGON‘) # obj.name=‘EGON‘ print(obj.name) # Egon # 4、delattr() delattr(obj,‘name‘) # del obj.name print(obj.__dict__)
获取对象和类的属性
res1=getattr(obj,‘say‘) # obj.say res2=getattr(People,‘say‘) # People.say print(res1) # <bound method People.say of <__main__.People object at 0x0167B0B8>> print(res2) # <function People.say at 0x016783D0>
利用反射,我们可以十分方便的判断从文件中读取的字符串,以及用户键入的字符串属性,是否在当前类中,并判断是否执行
class Ftp: def put(self): print(‘正在执行上传功能‘) def get(self): print(‘正在执行下载功能‘) def interactive(self): method=input(">>>: ").strip() # method=‘put‘ if hasattr(self,method): getattr(self,method)() else: print(‘输入的指令不存在‘) obj=Ftp() obj.interactive()
定义在类内部,以__开头并以__结果的方法
特点:会在某种情况下自动触发执行
为了定制化我们的类or对象
__str__:在打印对象时会自动触发,然后将返回值(必须是字符串类型)当做本次打印的结果输出
class People: def __init__(self, name, age): self.name = name self.age = age def __str__(self): # print(‘运行了...‘) return "<%s:%s>" %(self.name,self.age) obj = People(‘辣白菜同学‘, 18) # print(obj.__str__()) print(obj) # <‘辣白菜同学‘:18> # obj1=int(10) # 10.__str__() # print(obj1) # 10
__del__:在清理对象时触发,会先执行该方法 (类似于C++中的析构函数)
class People: def __init__(self, name, age): self.name = name self.age = age self.x = open(‘a.txt‘,mode=‘w‘) # self.x = 占据的是操作系统资源 def __del__(self): # print(‘run...‘) # 发起系统调用,告诉操作系统回收相关的系统资源 self.x.close() obj = People(‘辣白菜同学‘, 18) # del obj # obj.__del__() print(‘============>‘)
原文:https://www.cnblogs.com/zhubincheng/p/12708645.html