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
    不忘初心,方得始终
  • 相关阅读:
    移动端web初体验
    网页布局框架
    CSS 3D翻转相册动画特效
    move.js框架
    js照片墙拖拽特效
    团队编程项目作业2-团队编程项目开发环境搭建过程
    课后作业-阅读任务-阅读提问-1
    团队编程项目作业3
    阅读提问-2
    结对编程项目作业5
  • 原文地址:https://www.cnblogs.com/ducklu/p/8927254.html
Copyright © 2011-2022 走看看