Python hasattr,getattr,setattr,delattr
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # 作者:Presley 4 # 邮箱:1209989516@qq.com 5 # 时间:2018-11-04 6 # 反射使用 7 import sys 8 class WebServer(object): 9 def __init__(self,host,port): 10 self.host = host 11 self.port = port 12 def start(self): 13 print("Server is starting...") 14 def stop(self): 15 print("Server is stopping...") 16 def restart(self): 17 self.stop() 18 self.start() 19 20 def test_run(ins,name): 21 print("running...",name,ins.host) 22 23 if __name__ == "__main__": 24 server = WebServer("localhost",333) 25 '''#方法1 26 # #print(sys.argv[1]) 27 # cmd_dic = { 28 # "start":server.start, 29 # "stop":server.stop 30 # } 31 # if sys.argv[1] in cmd_dic: 32 # cmd_dic[sys.argv[1]]()''' 33 34 #1、hasattr,getattr 35 #方法二 36 if hasattr(server,sys.argv[1]): 37 func = getattr(server,sys.argv[1]) #获取server.start方法的内存地址 38 func() #相当于server.start() 39 40 #2、setattr 41 ''' 42 setattr(server,"run",test_run) #给实例绑定一个test_run方法,方法名字叫run 43 server.run(server,"wohaoshuai")#绑定的方法调用类中属性需要传入对象名称 44 ''' 45 #3、delattr 46 delattr(WebServer,"start") 47 server.restart()#报错