1

为什么在Python代码中装饰器很重要

 3 years ago
source link: http://developer.51cto.com/art/202102/645688.htm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

01什么是装饰器?

yeqeEz2.jpg!mobile

要理解什么是装饰器,您首先需要熟悉Python处理函数的方式。从它的观点来看,函数和对象没有什么不同。它们有属性,可以重新分配:

def func():  
  print('hello from func')  
func()  
> hello from func  
new_func = func  
new_func()  
> hello from func  
print(new_func.__name__)  
> func 

此外,你还可以将它们作为参数传递给其他函数:

def func():  
  print('hello from func')  
def call_func_twice(callback):  
  callback()  
  callback()  
call_func_twice(func)  
> hello from func  
> hello from func 

现在,我们介绍装饰器。装饰器(decorator)用于修改函数或类的行为。实现这一点的方法是定义一个返回另一个函数的函数(装饰器)。这听起来很复杂,但是通过这个例子你会理解所有的东西:

def logging_decorator(func): 
  def logging_wrapper(*args, **kwargs): 
    print(f'Before {func.__name__}') 
    func(*args, **kwargs) 
    print(f'After {func.__name__}') 
  return logging_wrapper 
     
@logging_decorator 
def sum(x, y): 
  print(x + y) 
   
sum(2, 5) 
> Before sum 
> 7 
> After sum 

让我们一步一步来:

  1. 首先,我们在第1行定义logging_decorator函数。它只接受一个参数,也就是我们要修饰的函数。
  2. 在内部,我们定义了另一个函数:logging_wrapper。然后返回logging_wrapper,并使用它来代替原来的修饰函数。
  3. 在第7行,您可以看到如何将装饰器应用到sum函数。
  4. 在第11行,当我们调用sum时,它不仅仅调用sum。它将调用logging_wrapper,它将在调用sum之前和之后记录日志。

02为什么需要装饰器

这很简单:可读性。Python因其清晰简洁的语法而备受赞誉,装饰器也不例外。如果有任何行为是多个函数共有的,那么您可能需要制作一个装饰器。下面是一些可能会派上用场的例子:

  1. 在运行时检查实参类型
  2. 基准函数调用
  3. 缓存功能的结果
  4. 计数函数调用
  5. 检查元数据(权限、角色等)
  6. 元编程

和更多…

现在我们将列出一些代码示例。

03例子

带有返回值的装饰器

假设我们想知道每个函数调用需要多长时间。而且,函数大多数时候都会返回一些东西,所以装饰器也必须处理它:

def timer_decorator(func): 
  def timer_wrapper(*args, **kwargs): 
    import datetime                  
    before = datetime.datetime.now()                      
    result = func(*args,**kwargs)                 
    after = datetime.datetime.now()                       
    print "Elapsed Time = {0}".format(after-before)       
    return result 
     
@timer_decorator 
def sum(x, y): 
  print(x + y) 
  return x + y 
   
sum(2, 5) 
> 7 
> Elapsed Time = some time 

可以看到,我们将返回值存储在第5行的result中。但在返回之前,我们必须完成对函数的计时。这是一个没有装饰者就不可能实现的行为例子。

带有参数的装饰器

有时候,我们想要一个接受值的装饰器(比如Flask中的@app.route('/login'):

def permission_decorator(permission): 
  def _permission_decorator(func): 
    def permission_wrapper(*args, **kwargs): 
      if someUserApi.hasPermission(permission): 
        result = func(*args, **kwargs) 
        return result 
      return None 
    return permission wrapper 
  return _permission_decorator 
 
@permission_decorator('admin') 
def delete_user(user): 
  someUserApi.deleteUser(user) 

为了实现这一点,我们定义了一个额外的函数,它接受一个参数并返回一个装饰器。

带有类的装饰器

使用类代替函数来修饰是可能的。唯一的区别是语法,所以请使用您更熟悉的语法。下面是使用类重写的日志装饰器:

class Logging:  
   
    def __init__(self, function):  
        self.function = function  
   
    def __call__(self, *args, **kwargs): 
      print(f'Before {self.function.__name__}') 
      self.function(*args, **kwargs) 
      print(f'After {self.function.__name__}') 
   
   
@Logging 
def sum(x, y): 
  print(x + y) 
 
sum(5, 2) 
> Before sum 
> 7 
> After sum 

这样做的好处是,您不必处理嵌套函数。你所需要做的就是定义一个类并覆盖__call__方法。

装饰类

有时,您可能想要修饰类中的每个方法。你可以这样写

class MyClass:  
  @decorator  
  def func1(self):  
    pass  
  @decorator  
  def func2(self):  
    pass 

但如果你有很多方法,这可能会失控。值得庆幸的是,有一种方法可以一次性装饰整个班级:

def logging_decorator(func): 
  def logging_wrapper(*args, **kwargs): 
    print(f'Before {func.__name__}') 
    result = func(*args, **kwargs) 
    print(f'After {func.__name__}') 
    return result 
  return logging_wrapper 
 
def log_all_class_methods(cls): 
    class NewCls(object): 
      def __init__(self, *args, **kwargs): 
        self.original = cls(*args, **kwargs) 
       
      def __getattribute__(self, s): 
        try:     
          x = super(NewCls,self).__getattribute__(s) 
        except AttributeError:       
          pass 
        else: 
          return x 
        x = self.original.__getattribute__(s) 
        if type(x) == type(self.__init__):  
          return logging_decorator(x)                  
        else: 
          return x 
    return NewCls 
     
@log_all_class_methods 
class SomeMethods: 
  def func1(self): 
    print('func1') 
     
  def func2(self): 
    print('func2') 
     
methods = SomeMethods() 
methods.func1() 
> Before func1 
> func1 
> After func1 

现在,不要惊慌。这看起来很复杂,但逻辑是一样的:

  • 首先,我们让logging_decorator保持原样。它将应用于类的所有方法。
  • 然后我们定义一个新的装饰器:log_all_class_methods。它类似于普通的装饰器,但却返回一个类。
  • NewCls有一个自定义的__getattribute__。对于对原始类的所有调用,它将使用logging_decorator装饰函数。

内置的修饰符

您不仅可以定义自己的decorator,而且在标准库中也提供了一些decorator。我将列出与我一起工作最多的三个人:

@property -一个内置插件的装饰器,它允许你为类属性定义getter和setter。

@lru_cache - functools模块的装饰器。它记忆函数参数和返回值,这对于纯函数(如阶乘)很方便。

@abstractmethod——abc模块的装饰器。指示该方法是抽象的,且缺少实现细节。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK