标签:python 反射
1.hasattr和getattr
#!/usr/bin/env python #-*- coding:utf-8 –*- import sys class WebServer(object): def __init__(self,host,port): self.ip = host self.port = port def start(self): print("start server..") def stop(self): print("stop server..") def restart(self): self.stop() self.start() if __name__ == ‘__main__‘: server = WebServer("localhost",333) if hasattr(server,sys.argv[1]): func = getattr(server,sys.argv[1]) func()
2.setattr
#!/usr/bin/env python #-*- coding:utf-8 –*- import sys class WebServer(object): def __init__(self,host,port): self.ip = host self.port = port def test_run(name): print("running...",name) if __name__ == ‘__main__‘: server = WebServer("localhost",333) setattr(server,"run",test_run) server.run("jack")
3.delattr
import sys class WebServer(object): def __init__(self,host,port): self.host = host self.port = port def test_run(name): print("running...",name) if __name__ == ‘__main__‘: server = WebServer("localhost",333) delattr(server,‘port‘)
本文出自 “AMY” 博客,请务必保留此出处http://amy2015.blog.51cto.com/11407620/1774912
标签:python 反射
原文地址:http://amy2015.blog.51cto.com/11407620/1774912