python反射
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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反射的主要内容,如果未能解决你的问题,请参考以下文章