简体   繁体   English

哪些函数不能在 Python 中修饰?

[英]What functions cannot be decorated in Python?

In a college test or interview question setting, how could you answer:在大学考试或面试问题设置中,您如何回答:

What functions can't be decorated in Python?哪些函数不能在 Python 中修饰?

It's beneficial to demonstrate depth of knowledge, so I would begin by briefly describing the uses of decorators in Python.展示知识深度是有益的,因此我将首先简要描述 Python 中装饰器的使用。 What are their limitations?它们的局限性是什么?

I've read the Decorator pattern Wiki and can't find any anti-patterns.我已经阅读了Decorator 模式 Wiki ,但找不到任何反模式。

A. Decorator uses A. 装饰器使用

  1. Decorators in Python are useful to extend the functionality of module functions, class methods, and classes themselves. Python 中的装饰器可用于扩展模块函数、类方法和类本身的功能。 For example, using a debug logging wrapper to a function or a dynamic programming cache:例如,将调试日志包装器用于函数或动态编程缓存:
@functools.lru_cache(maxsize=128)
def fibonacci(n=10):
    ...
  1. A class can also act as a decorator (if you implement the __init__() and __call__() methods).类还可以充当装饰器(如果您实现了__init__()__call__()方法)。

  2. A decorator can be wrapped to allow passing of arguments.可以包装装饰器以允许传递参数。 It can also be chained with other decorators.它也可以与其他装饰器链接。

B. When can't you use a decorator B. 什么时候不能使用装饰器

  1. You cannot use a decorator for variable assignments, calling functions etc. They are only used when defining a function/class/method.您不能将装饰器用于变量赋值、调用函数等。它们仅在定义函数/类/方法时使用。

  2. You may not want to use a decorator on a recursive function as it effectively halves the maximum recursion depth (as suggested by @jasonharper).您可能不想在递归函数上使用装饰器,因为它有效地将最大递归深度减半(如@jasonharper 所建议的)。

Are there any other cases when a decorator couldn't ( or shouldn't ) be used?还有其他情况下不能(或不应该)使用装饰器吗?

Maybe I got it wrong, but if you are not using syntactic sugar of the decorator ("@my_decorator"), then it's used via assigning a decorated function to a function you would like to decorate.也许我弄错了,但是如果您没有使用装饰器的语法糖(“@my_decorator”),那么它是通过将装饰函数分配给您想要装饰的函数来使用的。 So technically speaking, decorator can be used in assigning, not only in function definition, but function assigning to the other function:所以从技术上讲,装饰器可以用于赋值,不仅可以用于函数定义,还可以用于将函数赋值给另一个函数:

# let's create a simple decorator
def mydecorator(decorated_func):
    def wrapped(*args, **kwargs):
        print("Something happened in decorator!")
        return decorated_func(*args, **kwargs)
    return wrapped


# let's use decorator with syntactic sugar "@"
@mydecorator
def myfunc(myarg):
    print("my function", myarg)


# just simple function
def mysecond_func(myarg):
    print("my second function", myarg)

# let's decorate the second function with the same decorator,
# but without using syntactic sugar;
# it's identical with the first example with "@"
mysecond_func = mydecorator(mysecond_func)

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

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