在Python中反思给定函数的嵌套(局部)函数 [英] Introspecting a given function's nested (local) functions in Python
问题描述
给定函数
def f():
x,y = 1,2
def get():
print'get'
def post():
print'post'
有没有办法让我以我可以称之为的方式访问其本地的get()和post()函数?我正在寻找一个可以像上面定义的函数f()一样工作的函数:
>>> ; get,post = get_local_functions(f)
>>> get()
'get'
我可以访问这些本地函数的代码对象因此
在f.func_code.co_consts中导入检查
:
如果inspect.iscode(c ):
print c.co_name,c
导致
get< code object at at 0x26e78 ...>
发布< code object post at 0x269f8 ...>
但我无法弄清楚如何获得实际的可调用函数对象。这甚至有可能吗?
感谢您的帮助,
会。
导入检查
导入新的
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, c
which 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中反思给定函数的嵌套(局部)函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!