简体   繁体   English

python装饰函数调用

[英]python decorate function call

I recently learned about decorators and wondered if it's possible to use them not in a function definition but in a function call, as some kind of general wrapper. 我最近了解了装饰器,并想知道是否有可能不在某种函数定义中而是在函数调用中使用它们作为某种通用包装器。

The reason for that is, that I want to call functions from a module through a user-defined interface that does repeatable things to a function and I don't want to implement a wrapper for every single function. 这样做的原因是,我想通过用户定义的接口从模块调用函数,而该接口对函数执行可重复的操作,并且我不想为每个函数实现包装器。

In principle I would like to have something like 原则上我想

def a(num):
    return num

@double
a(2)

returning 4 without the need of having access to the implementation of a . 返回4,而不需要有机会获得实施的a Or would in this case a global wrapper like 或者在这种情况下,像

def mutiply(factor,function,*args,**kwargs):
    return factor*function(*args,*kwargs)

be the better choice? 是更好的选择?

There is a very good detailed section on decorators in Marty Alchin's book Pro Python from Apress. Marty Alchin在Apress撰写的Pro Python书中有非常详细的关于装饰器的部分。

While the new style @decorator syntax is only available to be used at function/class definition, you can use the older syntax, which does the same thing this way: 虽然仅在函数/类定义中可以使用新样式的@decorator语法,但是您可以使用较旧的语法,这种方式的作用相同:

from module import myfunc

myfunc = double_decorator(myfunc)

x = myfunc(2) # returns 4

You could do something like that: 您可以这样做:

def a(num):
    return num * 1

def double(f):
    def wrapped(*args, **kwargs):
        return f(*args, **kwargs)
    return wrapped

print(double(a)(2))

It's because we can decorate functions and run functions using a decorator function explicit as in the example above. 这是因为我们可以使用显式的装饰器函数来装饰函数并运行函数,如上例所示。 So in this one: 所以在这个:

print(double(a)(2))

In the place of a you can put any function and in place of the 2 , args and kwargs. 在的地方a你可以把任何功能和到位的2 ,指定参数和kwargs。

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

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