简体   繁体   中英

Decorating a class that has been defined already

I am trying to add fucntionality to a general class from a library. I defined a function that takes as input a general class from library, defines a class that has the general class from library as parent, and returns such class. I want to treat this function as a decorator.

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


If I pass the previously defined library_class to the decorator it throws me an error

@decorator
library_class

Just use the function-calling syntax, instead of the special decorator syntax, using @ . In this case:


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)

The decorator syntax, used by placing the @decorator preceeding a function, and later a class declaration, was created back in Python 2.3, exactly as a shortcut for function = decorator(function) , and its advantage is just that the decorator can be declared along with the function, and there is no need to repeat its name. Other than that, it just means that the function (or class) in this case is passed as the sole parameter to the decorator, and the returned value assumes the function (or class) name in the current scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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