在Python中调用嵌套函数 [英] Call Nested Function in Python

查看:598
本文介绍了在Python中调用嵌套函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法可以分解成较小的嵌套函数来拆分代码库:

I have a method that i have broken into smaller nested functions to break up the code base:

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

是否有一种方法可以单独运行其中一个嵌套函数.例如:

Is there a way to run one of the nested functions by itself. eg:

foo.do_this(x,y)

我正在尝试在我使用pyramid_breaker构建的Web服务器上设置缓存

I am trying to setup caching on a web server i have built using pyramid_breaker

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)

这是我的理解,可能不准确:

This is my understanding may not be accurate:

现在我有这个原因是因为装饰器用来创建缓存键的名称空间是从函数和争论中产生的.因此,您不能仅将装饰器放在getThis上,因为请求变量是唯一的,并且缓存是无用的.因此,我创建了具有可重复参数(search_term)的内部函数.

Now the reason i have this is that the namespace used by the decorator to create the cache key is genereated from the function and the arguements. You can't therefore just put the decorator on getThis as the request variable is unique-ish and the cache is useless. So i created the inner function which has repeatable args (search_term).

但是,要使缓存无效(即刷新),无效功能需要作用域来了解"getData"功能,因此也需要嵌套.因此,我需要调用嵌套函数.你们真是太好了,人们已经清楚地表明这是不可能的,所以有人能够解释我如何用不同的结构来做到这一点吗?

However to invalidate the cache (ie refresh), the invalidation function requires scope to know of the 'getData' function so also needs to be nested. Therefore i need to call the nested function. You wonderful people have made it clear its not possible so is someone able to explain how i might do it with a different structure?

推荐答案

我假设do_thisdo_that实际上依赖于foo的某些参数,因为否则您可以将它们移出foo并直接给他们打电话.

I assume do_this and do_that are actually dependent on some argument of foo, since otherwise you could just move them out of foo and call them directly.

我建议将整个课程重新制作为一堂课.像这样:

I suggest reworking the whole thing as a class. Something like this:

class Foo(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def do_this(self):
        pass

    def do_that(self):
        pass

    def __call__(self):
        self.do_this()
        self.do_that()

foo = Foo(x, y)
foo()
foo.do_this()

这篇关于在Python中调用嵌套函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆