zoukankan      html  css  js  c++  java
  • python中通过字典实现函数指针

    用字典的key-value代替if语句;并且value为函数的引用,实现c语言中函数指针的思想。

    URL_FUNC_DICT= dict()  # 全局变量;将函数引用保存为字典的value
    
    def route(url):  
    	def set_func(func):
    		URL_FUNC_DICT[url] = func
    		def call_func(*args, **kwargs):		
    			return func(*args, **kwargs)
    		return call_func
    	return set_func
    
    @route("/index.py")  # 带参数的装饰器
    def index():
    	with open("./templates/index.html") as f:
    		content = f.read()
    	
    	my_stock_info = "哈哈哈哈 这是你的本月名称...."
    	
    	content = re.sub(r"{%content%}", my_stock_info, content)
    	
    	return content
    
    @route("/center.py")
    def center():
    	with open("./templates/center.html") as f:
    		content = f.read()
    
    	my_stock_info = "这里是从mysql查询出来的数据。。。"
    	
    	content = re.sub(r"{%content%}", my_stock_infor, content)
    
    	return content
    
    try:
    	return URL_FUNC_DICT[file_name]  # 代替if语句,由字典key-value映射关系代替if语句
    except Exception as ret:
    	return "产生了异常:%s" % str(ret)
    
    
  • 相关阅读:
    thinkphp SAE
    thinkphp rpc
    thinkphp REST
    thinkphp 图形处理
    thinkphp 验证码
    thinkphp 文件上传
    thinkphp 数据分页
    thinkphp 多语言支持
    thinkphp cookie支持
    thinkphp session支持
  • 原文地址:https://www.cnblogs.com/bitbitbyte/p/12536600.html
Copyright © 2011-2022 走看看