本文介绍了在Python中反思给定函数的嵌套(局部)函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定函数
导入检查
导入新的
def f():
x,y = 1,2
def get():
print'get'
def post():
print'post'
for f.func_code.co_consts:
if inspect.iscode(c):
f = new.function(c,globals())
print f#这里有你的函数:]。
但是为什么会这样呢?使用课程不容易吗?无论如何,Instantiation看起来像是一个函数调用。
Given the function
def f(): x, y = 1, 2 def get(): print 'get' def post(): print 'post'is there a way for me to access its local get() and post() functions in a way that I can call them? I'm looking for a function that will work like so with the function f() defined above:
>>> get, post = get_local_functions(f) >>> get() 'get'I can access the code objects for those local functions like so
import inspect for c in f.func_code.co_consts: if inspect.iscode(c): print c.co_name, cwhich results in
get <code object get at 0x26e78 ...> post <code object post at 0x269f8 ...>but I can't figure out how to get the actual callable function objects. Is that even possible?
Thanks for your help,
Will.
解决方案You are pretty close of doing that - just missing new module:
import inspect import new def f(): x, y = 1, 2 def get(): print 'get' def post(): print 'post' for c in f.func_code.co_consts: if inspect.iscode(c): f = new.function(c, globals()) print f # Here you have your function :].But why the heck bother? Isn't it easier to use class? Instantiation looks like a function call anyway.
这篇关于在Python中反思给定函数的嵌套(局部)函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!