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 look at the class and how a Python decorator works.
The Python decorator for a class
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
How to use the Python decorator
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.
If you are not yet familiar with Spark, have a look at the Spark Tutorial i created here. Also, I will create more tutorials on Python and Machine Learning in the future, so make sure to check back often to the Big Data & Data Science tutorial overview. I hope you liked this tutorial. If you have any suggestions and what to improve, please feel free to get in touch with me! If you want to learn more about Python, I also recommend you the official page.
Leave a ReplyWant to join the discussion?
Feel free to contribute!