一根据用户的输入, 执行对象方法
例如:
- class Service:
- def run(self):
- while True:
- cmd = input(>>: ).strip()
- if hasattr(self, cmd):
- func = getattr(self, cmd)
- func()
- print(cmd)
- def get(self):
- print(get.......)
- def put(self):
- print(put.......)
- obj = Service()
- obj.run()
结果为:
- >>: get
- get.......
- get
- >>: put
- put.......
- put
- >>: xxxx
- xxxx
- >>:
有用户选择的方法的话执行, 没有的话就不会执行
还可以对上述代码进行改进, 如下:
- class Service:
- def run(self):
- while True:
- inp = input(>>: ).strip()
- cmds = inp.split()
- print(cmds)
- if hasattr(self, cmds[0]):
- func = getattr(self, cmds[0])
- func(cmds)
- def get(self, cmds):
- print(get......., cmds)
- def put(self, cmds):
- print(put......., cmds)
- obj = Service()
- obj.run()
结果为:
- >>: get a.txt
- [get, a.txt]
- get....... [get, a.txt]
- >>: put b.txt
- [put, b.txt]
- put....... [put, b.txt]
- >>:
来源: http://www.bubuko.com/infodetail-2535770.html