python中利用exec动态创建函数

# -*- coding: utf-8 -*- 
import time
import datetime
import os
import sys 

def defFunciton(temp_namepace):
	'''在命名空间 temp_namepace中定义两个函数'''
	function_str = '''
def GET(str1):
	return str1 + "GET_test1"
		'''	
	exec(function_str,temp_namepace)	#####在命令空间 temp_namepace 中声明一个函数
	function_str = u'''		####注意字符串的编码也可以不是unicode
def GET(str1):
	def printHello():		####注意这里在函数里面定义了一个函数
		print u"GET start..."
	printHello()	
	return str1 + "GET_test2"
		'''	
	exec(function_str,temp_namepace)	
	
if __name__ == '__main__':
	a = "word"
	exec('a="hello"')	####exec后面代码将在当前域执行
	print a		#### "hello",因为exec的代码改变了a 
	
	a = "word"
	exec('a="hello"',{})	####指明exec的代码在一个无名作用域
	print a	#### "word",因为exec的代码改变的是无名作用域内的a

	temp_namepace = {"a":"MMMM"}
	exec('a="hello"',temp_namepace)		####指明exec的代码在一个无名作用域,
	print a		#### "word",因为exec的代码改变的是temp_namepace作用域内的a
	print temp_namepace["a"]	#### "hello",因为exec的代码改变的是temp_namepace作用域内的a
	a = temp_namepace["a"]	#####把temp_namepace作用域内的a拷贝出来
	print a			#### "hello"	

	temp_namepace = {}
	exec('a="hello"',temp_namepace)		#####限定exec语句的执行空间
	exec('b="hello"',temp_namepace)	
	exec('c=a+"&&&"+b',temp_namepace)
	print temp_namepace["c"]
	print temp_namepace.keys()

	defFunciton(temp_namepace)		####在命名空间 temp_namepace 中
	print temp_namepace.keys()		######尽管exec了多次,但是其所在的命令空间中却只有一个"GET"
	func_str = "GET"
	para_str = "kkkk"
	print temp_namepace[func_str](para_str)		####注意调用的方式 

运行结果为:


猜你喜欢

转载自blog.csdn.net/wjj547670933/article/details/50489196
今日推荐