简体   繁体   English

Python-在包装函数命名后调用包装函数

[英]Python - calling wrapper function after naming function it wraps

I honestly don't know if this is good, bad, neutral, whatever. 老实说,我不知道这是好是坏,中立等等。

def foo():
    return "foo called"

def bar():
    return "BAR CALLED"

def wrap(func):
    def _(*args, **kwargs):
        try:
            func.counter += 1
        except:
            func.counter = 0
        print "The count is %d" % func.counter
        return func(*args, **kwargs)
    return _

>>> foo = wrap(foo)
>>> bar = wrap(bar)
>>> foo()
'The count is 0'
'foo called'
>>> foo()
'The count is 1'
'foo called'
>>> bar()
'The count is 0'
'BAR CALLED'

So far, so good -- functions are just wrapped, no big deal. 到目前为止,一切都很好-函数只是包装而已,没什么大不了的。 Here's the bit that I don't know whether to consider a feature or not. 这是我不知道是否考虑功能的一点。

>>> foo
<function _ at 0x100499ed8>
>>> _()
The count is 2
'foo called'
>>> bar
<function _ at 0x10049f320>
>>> _()
The count is 1
'BAR CALLED'
>>> 

Perhaps I know too little of the behind-the-scenes here, but Python has two wrapper functions in memory named _ , and a user can apparently 'switch' between them by just typing the name of the function it wraps. 也许我对这里的幕后知识了解得很少,但是Python在内存中有两个名为_包装函数,并且用户显然可以通过键入其包装的函数名称在它们之间“切换”。

Is this a feature, and if it is, what would its primary application be? 这是一个功能吗?如果是,它的主要应用程序是什么? Or if it is not, is this best left forgotten about, because it's just a Bad Idea to try and featurize this behavior? 或者,如果不是,最好忘记这一点,因为尝试使这种行为美化只是一个坏主意? My journeyman guess is that this is only doable because there are not real closures in Python (which probably puts it under We're all adults here and I should not ever try to actually do this), but that's an uneducated guess. 我的熟练工人猜测这仅是可行的,因为Python中没有真正的闭包(可能将其归类为“ We're all adults here ,所以我永远不要尝试实际这样做”),但这是没有根据的猜测。

That is a shortcut of the Python interpreter. 这是Python解释器的快捷方式。 The result of the last expression evaluated is assigned to _ so that you can use it in subsequent operations. 最后计算出的表达式的结果分配给_以便您可以在后续操作中使用它。

Like: 喜欢:

>>> 5 + 7
12
>>> _ * 2
24
>>> _ + 3
27

Please note that this will work only in an interactive shell, not in a script, and only when _ isn't already defined by you. 请注意,这仅在交互式外壳中有效,在脚本中无效,并且仅当您尚未定义_时才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM