Pthon魔术方法(Magic Methods)-反射
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.反射概述
运行时,区别于编译时,指的时程序被加载到内存中执行的时候。
反射,reflection,指的时运行时获取类型定义信息。
一个对象能够再运行时,像照镜子一样,反射出其类型信息。
简单的说,再python这种,能够通过一个对象,找出其type,class,attribute或method的能力,称为反射或者自省。
具有反射能力的函数有type(),isinstance(),callable(),dir(),getattr()等。
二.反射相关的函数和方法
1>.看一个简单需求
有一个Point类,查看它的实例的属性,并修改它。动态为实例增加属性
1 #!/usr/bin/env python 2 #_*_conding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie 5 6 7 class Point: 8 def __init__(self,x,y): 9 self.x = x 10 self.y = y 11 12 def __str__(self): 13 return "Point({},{})".format(self.x,self.y) 14 15 def show(self): 16 print(self.x,self.y) 17 18 p = Point(10,20) 19 print(p) 20 print(p.__dict__) 21 p.__dict__['y'] = 30 22 print(p.__dict__) 23 p.z = 10 24 print(p.__dict__) 25 print(dir(p)) 26 print(p.__dir__())
Point(10,20) {'x': 10, 'y': 20} {'x': 10, 'y': 30} {'x': 10, 'y': 30, 'z': 10} ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'show', 'x', 'y', 'z'] ['x', 'y', 'z', '__module__', '__init__', '__str__', 'show', '__dict__', '__weakref__', '__doc__', '__repr__', '__hash__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']