python 中的反射

反射中设计到两个内置函数 hasattr和getattr
hasattr:用于判断对象是否包含对应的属性。
getattr:用于返回一个对象属性值。

class Service:
    def run(self):
        while True:
            inp=input('>>: ').strip() #cmd='get a.txt'
            cmds=inp.split() #cmds=['get','a.txt']

            #print(cmds)
            if hasattr(self,cmds[0]):
                func=getattr(self,cmds[0])
                func(cmds)

    def get(self,cmds):
        print('这是get func',cmds)

    def put(self,cmds):
        print('这是 put func.......',cmds)

obj=Service()
obj.run()

    原文作者:wangcc_sd
    原文地址: https://www.jianshu.com/p/9048c3499b71
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞