标签:shu elf tar ping python get coding utf-8 server
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 作者:Presley
# 邮箱:1209989516@qq.com
# 时间:2018-11-04
# 反射使用
import sys
class 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()#报错
Python hasattr,getattr,setattr,delattr
标签:shu elf tar ping python get coding utf-8 server
原文地址:https://www.cnblogs.com/Presley-lpc/p/9903533.html