zoukankan      html  css  js  c++  java
  • Python----面向对象---反射的应用

    一、根据用户的输入,执行对象方法

    例如:

     1 class Service:
     2     def run(self):
     3         while True:
     4             cmd = input('>>: ').strip()
     5             if hasattr(self, cmd):
     6                 func = getattr(self, cmd)
     7                 func()
     8             print(cmd)
     9 
    10     def get(self):
    11         print('get.......')
    12 
    13     def put(self):
    14         print('put.......')
    15 
    16 
    17 obj = Service()
    18 obj.run()
    19 
    20 结果为:
    21 >>: get
    22 get.......
    23 get
    24 >>: put
    25 put.......
    26 put
    27 >>: xxxx
    28 xxxx
    29 >>: 

    有用户选择的方法的话执行,没有的话就不会执行

    还可以对上述代码进行改进,如下:

     1 class Service:
     2     def run(self):
     3         while True:
     4             inp = input('>>: ').strip()
     5             cmds = inp.split()
     6             print(cmds)
     7             if hasattr(self, cmds[0]):
     8                 func = getattr(self, cmds[0])
     9                 func(cmds)
    10 
    11 
    12     def get(self, cmds):
    13         print('get.......', cmds)
    14 
    15     def put(self, cmds):
    16         print('put.......', cmds)
    17 
    18 
    19 obj = Service()
    20 obj.run()
    21 
    22 结果为:
    23 
    24 >>: get a.txt
    25 ['get', 'a.txt']
    26 get....... ['get', 'a.txt']
    27 >>: put b.txt
    28 ['put', 'b.txt']
    29 put....... ['put', 'b.txt']
    30 >>: 
  • 相关阅读:
    P3391 文艺平衡树
    隔离村庄(树形dp[01背包])
    cmd指令集
    vs的使用
    博客园第一天
    蓝桥杯 小生物的逃逸 模拟
    蓝桥杯 自行车停放 双向链表
    c++字符数组函数总结
    蓝桥杯 石子游戏 贪心
    蓝桥杯 最大获利 模拟
  • 原文地址:https://www.cnblogs.com/xudachen/p/8626864.html
Copyright © 2011-2022 走看看