Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 对每个函数都有效的装饰器_Python_Python Decorators - Fatal编程技术网

Python 对每个函数都有效的装饰器

Python 对每个函数都有效的装饰器,python,python-decorators,Python,Python Decorators,我想在每个函数调用上打印Hello World,我正在使用装饰器来实现这一点 def hello_decorator(fn): def ret_fn(*args, **kwargs): print("Hello world") return fn(*args, **kwargs) return ret_fn 假设这导致函数出错,而该函数的未修饰版本工作正常,那么装饰器会有什么问题?问题不在于打印,因为我可以删除它,问题仍然存在 有没有更好的方法包

我想在每个函数调用上打印Hello World,我正在使用装饰器来实现这一点

def hello_decorator(fn):
    def ret_fn(*args, **kwargs):
        print("Hello world")
        return fn(*args, **kwargs)
    return ret_fn
假设这导致函数出错,而该函数的未修饰版本工作正常,那么装饰器会有什么问题?问题不在于打印,因为我可以删除它,问题仍然存在


有没有更好的方法包装函数并以没有原型的方式调用它?

装饰程序必须返回函数

def hello_decorator(fn):
    def ret_fn(*args, **kwargs):
        print("Hello world")
        return fn(*args, **kwargs)
    return ret_fn

这不是有效的装饰程序。装饰程序应该返回一个函数。看看。你所说的“在没有原型的情况下调用”是什么意思。你能进一步解释一下吗?@LaurentLAPORTE在不知道原型的情况下照着原话读。我的意思是,你如何在不知道它的原型的情况下装饰一个任意函数?@1419636215就像你现在做的一样,通过直接传递
*args
**kwargs
。此外,您还可以使用来保留修饰函数的更多详细信息(例如名称、docstring等)。对此表示抱歉。我已经编辑了问题中的代码。