Decorators are powerful things in most programming languages. They help us making code more readable and adding functionality to a method or class. Basically, decorators are added above the method or class declaration in order to create some behaviour. Basically, we differentiate between two kind of decorators: method decorators and class decorators. In this tutorial, we will have a look at Class decorators.
Class decorators are used to add some behaviour to a class. Normally, you would use this when you want to add some kind of behaviour to a class that is outside of its inheritance structure – e.g. by adding something that is too abstract to bring it to the inheritance structure itself.
The definition of that is very similar to the method decorators:
The decorator definition is also very similar to the last tutorial’s sample. We first create a method that takes a class and then create the inner method. Within the inner method, we create a new function that we want to “append” to the class. We call this method “fly” that simply prints “Now flying …” to the console. To add this function to the class, we call the “setattr” function of Python. We then return the class and the class wrapper.
def altitude(cls): def clswrapper(*args): def fly(): print("Now flying ... ") setattr(cls, "fly", fly) return cls return clswrapper
Now, our decorator is ready to be used. We first need to create a class. Therefore, we re-use the sample of the vehicles, but simplify it a bit. We create a class “Vehicle” that has a function “accelerate” and create two sub classes “Car” and “Plane” that both inherit from “Vehicle”. The only difference now is that we add a decorator to the class “Plane”. We want to add the possibility to fly to the Plane.
class Vehicle: speed = 0 def accelerate(self, speed): self.speed = speed class Car(Vehicle): pass @altitude class Plane(Vehicle): pass
Now, we want to test our output:
c = Car() p = Plane() c.accelerate(100) print(c.speed) print(p.fly())
100 Now flying ...
Basically, there are a lot of scenarios when you would use class decorators. For instance, you can add functionality to classes that contain data in order to convert this into a more readable table or alike.
In our next tutorial, we will look at the await-operator.