需求:

因为最近在看python脚本脚本获取oracle数据库数据进行oracle数据库监控,需要用到反射的方式做,去通过传参调用不同函数去获取不同的数据库状态(python2)

#!/usr/bin/pythonclass Exucutsql(object):    def status(self):        print("active")    def db(self):        print("100M")class Main(Exucutsql):    def __init__(self):        pass    def __call__(self):        method = raw_input("please input your method:")        if hasattr(self,method):            func = getattr(self, method)            func()        else:            print("input method is not exits")if __name__ == "__main__":    Main()

说明:输入相应方法名会调用不用的方法

python类中的特殊方法

__call__() 方法会当作一个函数去执行

hasattr() 方法会判断在类中是否存在方法

getattr() 方法会去调用执行相应的函数名方法(解决了过多的IF判断的问题)