#!/usr/bin/env python# -*- coding:utf-8 -*-# 作者:Presley# 邮箱:[email protected]# 时间:2018-11-04# 反射使用import sysclass WebServer(object): def __init__(self,host,port): self.host = host self.port = port def start(self): print("Server is starting...") def stop(self): print("Server is stopping...") def restart(self): self.stop() self.start() def test_run(ins,name): print("running...",name,ins.host) if __name__ == "__main__": server = WebServer("localhost",333) ‘‘‘#方法1 # #print(sys.argv[1]) # cmd_dic = { # "start":server.start, # "stop":server.stop # } # if sys.argv[1] in cmd_dic: # cmd_dic[sys.argv[1]]()‘‘‘ #1、hasattr,getattr #方法二 if hasattr(server,sys.argv[1]): func = getattr(server,sys.argv[1]) #获取server.start方法的内存地址 func() #相当于server.start() #2、setattr ‘‘‘ setattr(server,"run",test_run) #给实例绑定一个test_run方法,方法名字叫run server.run(server,"wohaoshuai")#绑定的方法调用类中属性需要传入对象名称 ‘‘‘#3、delattr delattr(WebServer,"start") server.restart()#报错
原文地址:https://www.cnblogs.com/Presley-lpc/p/9903533.html
时间: 2024-11-09 20:20:52