【发布时间】:2012-06-22 10:41:00
【问题描述】:
我有一个方法,我已经分解成更小的嵌套函数来分解代码库:
def foo(x,y):
def do_this(x,y):
pass
def do_that(x,y):
pass
do_this(x,y)
do_that(x,y)
return
有没有办法自己运行其中一个嵌套函数。例如:
foo.do_this(x,y)
编辑:
我正在尝试在使用 pyramid_breaker 构建的 Web 服务器上设置缓存
def getThis(request):
def invalidate_data(getData,'long_term',search_term):
region_invalidate(getData,'long_term',search_term)
@cached_region('long_term')
def getData(search_term):
return response
search_term = request.matchdict['searchterm']
return getData(search_term)
这是我的理解可能不准确:
现在我有这个的原因是装饰器用来创建缓存键的命名空间是从函数和争论中生成的。因此,您不能只将装饰器放在 getThis 上,因为请求变量是唯一的并且缓存是无用的。所以我创建了具有可重复参数(search_term)的内部函数。
然而,为了使缓存失效(即刷新),失效函数需要知道“getData”函数的范围,因此也需要嵌套。因此我需要调用嵌套函数。你们这些了不起的人已经明确表示这是不可能的,那么有人能解释一下我如何用不同的结构来做到这一点吗?
【问题讨论】:
-
您的代码
foo.do_this将尝试将do_this 作为foo的成员函数访问,这会给您一个属性错误,而是将foo 作为一个类 -
“分解代码库”是模块命名空间的优点。如果您真的想封装
do_函数,请使用@lazyr 显示的类。 -
嵌套函数不是在 Python 中构造代码的方式(类也不是)。看看modules。
-
查看我的答案:*.com/questions/7054228/…