문제

Inside a function, I can use dir() to get a list of nested functions:

>>> def outer():
...  def inner(): pass
...  print dir()
...
>>> outer()
['inner']

...but then what? How can I access these functions by name? I see no __dict__ attribute.

도움이 되었습니까?

해결책

First: Are you sure you want to do this? It's usually not a good idea. That said,

def outer():
    def inner(): pass
    locals()['inner']()

You can use locals to get a dictionary of local variable values, then look up the value of 'inner' to get the function. Don't try to edit the local variable dict, though; it won't work right.


If you want to access the inner function outside the outer function, you'll need to store it somehow. Local variables don't become function attributes or anything like that; they're discarded when the function exits. You can return the function:

def outer():
    def inner(): pass
    return inner

nested_func = outer()
nested_func()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top