zoukankan      html  css  js  c++  java
  • hasattr(),getattr(),setattr()的使用

     1 # 首先你有一个command.py文件,内容如下,这里我们假若它后面还有100个方法
     2 
     3 class MyObject(object):
     4     def __init__(self):
     5         self.x = 9
     6     def add(self):
     7         return self.x + self.x
     8 
     9     def pow(self):
    10         return self.x * self.x
    11 
    12     def sub(self):
    13         return self.x - self.x
    14 
    15     def div(self):
    16         return self.x / self.x
    View Code
     1 # 然后我们有一个入口文件 exec.py,要根据用户的输入来执行后端的操作
     2 from command import MyObject
     3 computer=MyObject()
     4 
     5 def run():
     6     inp = input('method>')
     7 
     8     if inp == 'add':
     9         computer.add()
    10     elif inp == 'sub':
    11         computer.sub()
    12     elif inp == 'div':
    13         computer.div()
    14     elif inp == 'pow':
    15         computer.pow()
    16     else:
    17         print('404')
    View Code

    上面使用了if来进行判断,那么假若我的command里面真的有100个方法,那我总不可能写100次判断吧,所以这里我们就会用到python的反射特性,看下面的代码

     1 from command import MyObject
     2 
     3 computer=MyObject()
     4 def run(x):
     5     inp = input('method>')
     6     # 判断是否有这个属性
     7     if hasattr(computer,inp):
     8     # 有就获取然后赋值给新的变量
     9         func = getattr(computer,inp)
    10         print(func())
    11     else:
    12     # 没有我们来set一个
    13         setattr(computer,inp,lambda x:x+1)
    14         func = getattr(computer,inp)
    15         print(func(x))
    16 
    17 if __name__ == '__main__':
    18     run(10)
    View Code
    不忘初心,方得始终
  • 相关阅读:
    抚琴弹唱东流水
    借点阳光给你
    日月成双行影单
    一夜飘雪入冬来
    悼念钱学森
    我的青春谁作主
    重游望江楼有感
    雪后暖阳
    满城尽添黄金装
    敢叫岁月不冬天
  • 原文地址:https://www.cnblogs.com/ducklu/p/8927254.html
Copyright © 2011-2022 走看看