您的位置:首页 > 编程语言 > Python开发

python中利用exec动态创建函数

2016-01-09 19:41 681 查看
# -*- 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)		####注意调用的方式

运行结果为:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python exec