反射

python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。

在代码中使用反射能够使得我们的代码逻辑更加清楚,减少繁复的调用。

反射是这么用的:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

class MyTest(object):
    def __init__(self):
        self.name = "nuwanda"

    def handle(self,func_name):
        if hasattr(self,func_name):
           func = getattr(self,func_name)
           func()
        else:
           print "没有找到该方法"

#改掉类中的字段
    def set_field(self,value):
        if hasattr(self,"name"):
           setattr(self,"name",value)

#改掉类中的方法
    def set_func(self,value):
        if hasattr(self,"p"):
           setattr(self,"p",value)

#往类中添加一个字段
    def add_field(self,value):
        setattr(self,"age",value)

#往类中添加一个方法
    def add_func(self,value):
        setattr(self,"a",value)
#删除类中的某一个成员
    def del_member(self,name):
        if hasattr(self,name):
           delattr(self,name)
        else:
           print "没有这个成员!"

    def p(self):
        print "hahaha!"

    def x(self):
        print "我可以发文件!"

    def y(slef):
        print "我可以收文件!"
    
    def z(self):
        print "我可以远程执行命令!"

def pp():
    print "xixixi!"

f= MyTest()
f.handle("x")
f.handle("y")
f.handle("z")
f.handle("w")

print f.name
f.set_field("chenyao")
print f.name

f.p()
f.set_func(pp)
f.p()

f.add_field(18)
print f.age

f.add_func(pp)
f.a()
try:
    f.del_member("age")
    print f.age
except AttributeError,e:
    print "已经没有age属性"
try:
    f.del_member("x")
    f.p()
except AttributeError,e:
    print "已经没有x属性"
try:
   f.del_member("a")
   f.a()
except AttributeError,e:
   print "已经没有a属性"

执行结果: [root@vm_134 tmp]# python test.py 我可以发文件! 我可以收文件! 我可以远程执行命令! 没有找到该方法 nuwanda chenyao hahaha! xixixi! 18 xixixi! 已经没有age属性 已经没有x属性 已经没有a属性

    反射可以在类的外部对类中的成员进行操控 

在类中使用反射,可以反射出类中的成员(字段,方法)

在模块中使用反射,可以反射出模块中的变量,函数,类

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

def p():
    print "hahahaha"

class MyTest(object):
   def __init__(self):
       pass
   def f(self):
    print "xixixixi"

def handle(name):
    if hasattr(sys.modules[__name__],name):
       func = getattr(sys.modules[__name__],name)
       return func()    #如果是: return func  是可以反射变量的

handle("p")
a = handle("MyTest")
a.f()

执行结果:
[root@vm_134 tmp]# python t.py 
hahahaha
xixixixi
原文地址:https://www.cnblogs.com/along1226/p/5673557.html