Python自动化运维开发----基础(十七)类的反射-创新互联

需求:

创新互联建站专注于企业成都全网营销推广、网站重做改版、正宁网站定制设计、自适应品牌网站建设、H5建站商城开发、集团公司官网建设、成都外贸网站建设公司、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为正宁等各大城市提供网站开发制作服务。

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

#!/usr/bin/python
class 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判断的问题)


网站名称:Python自动化运维开发----基础(十七)类的反射-创新互联
分享路径:http://ybzwz.com/article/dodspd.html