繁体   English   中英

装饰一个已经定义好的 class

[英]Decorating a class that has been defined already

我正在尝试从图书馆向一般 class 添加功能。 我定义了一个 function,它将库中的通用 class 作为输入,定义了一个 class,它以库中的通用 class 作为父级,并返回这样的 class。我想将这个 function 视为装饰器。

class library_class():
  def __init__(self):
    self.foo = bar

def decorator(general_library_class):
  class MyClass(general_library_class):
    def __init__(self):
      super().__init__()
    
  return MyClass


如果我将之前定义的 library_class 传递给装饰器,它会抛出一个错误

@decorator
library_class

只需使用函数调用语法,而不是使用@的特殊装饰器语法。 在这种情况下:


class library_class():
  def __init__(self):
    self.foo = bar

def decorator(general_library_class):
  class MyClass(general_library_class):
    def __init__(self):
      super().__init__()
    
  return MyClass


MyClass = decorator(library_class)

装饰器语法,通过将@decorator放在 function 之前,然后是 class 声明,在 Python 2.3 中创建,完全作为function = decorator(function)的快捷方式,它的优点只是可以声明装饰器与 function 一起,无需重复其名称。 除此之外,它只是意味着 function(或类)在这种情况下作为唯一参数传递给装饰器,并且返回值采用当前 scope 中的 function(或类)名称。

暂无
暂无

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

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