写出一个简单类:
import sys
class webserver(object):
def __init__(self,host,post):
self.host = host
self.post = post
def start(self):
print("server is starting...")
def stop(self):
print("server is stopping...")
def reload(self):
print("server is reloading...")
if __name__ == '__main__':
server = webserver('localhost',3033)
print(sys.argv[1])
#当你要调用类方法时:
#最low的方法为用:
if sys.argv[1] == 'start':
server.start()
代码重用太多,可以修改为将方法写成字典:
cmd_dic = {
'start':server.start,
'stop':server.stop,
'reload':server.reload}
if sys.argv[1] in cmd_dic:
cmd_dic['start']()
代码依然有重用,可以用反射的方法来解决:
if hasattr(server,sys.argv[1]):
func = getattr(server,sys.argv[1]) #获取server.start内存地址
func() #server.start()
反射是很好的写法,常用!
转载于:https://www.cnblogs.com/kinghtjdq/p/5278757.html