When we talk about decorating classes, we can either decorate individual methods or we can create a decorator to decorate the whole class.
class MyClass: def __init__(self, a): self.a = a @timer def method1(self, x, y): print('method1 executing') @timer def method2(self, x, y): print('method2 executing') @trace def method3(self, x, y): print('method3 executing')
Decorating methods is straightforward, it is like decorating functions only. For example, the decorators trace and timer that we have created in our lectures, can be applied to methods of a class to trace or time the method calls. While applying the decorators to methods of a class, we need to keep in mind that a method always receives the current instance as the first argument. The decorators trace and timer that we had created, will work properly with methods also because they are not doing anything special with the first argument but suppose you have a decorator that sanitizes the first argument of a function then you cannot simply apply that decorator to a method, because for methods, the current instance is the first argument, and the first argument that you send when you call the method is actually the second argument.
Now, let us see how to create a decorator function to decorate the class as a whole. This type of decorator function will take a class as the argument. It will either modify that class and return it, or it will create a new class and return it. Modifying the class in-place and returning the modified class is more convenient than creating a new class. So, we will see some examples where we will create a decorator that takes a class and returns the modified class.
The syntax for applying the decorator to a class will be the same. You can either use the automatic way or decorate the class manually.
@decorator class MyClass: pass class MyClass: pass MyClass = decorator(MyClass)
标签:methods,Python,argument,will,classes,Decorating,class,decorator,first From: https://www.cnblogs.com/zhangzhihui/p/18334748