Call Nested Function in Python(在 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_this
和 do_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 中调用嵌套函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中调用嵌套函数
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01