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
    不忘初心,方得始终
  • 相关阅读:
    课后总结
    构建之法阅读笔记01
    软件工程周总结02
    开课博客
    二维数组最大子数组和
    大二下周总结四
    大二下周总结三
    定义一个整型数组,返回该数组中子数组和的最大值
    软件工程开课
    定义一个数组返回最大子数组的值(1)
  • 原文地址:https://www.cnblogs.com/ducklu/p/8927254.html
Copyright © 2011-2022 走看看