Decoration is a way to specify management code for functions and classes. Decorators themselves take the form of callable objects that process other callable objects. A Class Decorator is similar to function decorators, but they are run at the end of a class statement to rebind a class name to a callable (e.g functions). As such, they can be used to either manage classes just after they are created or insert a layer of wrapper logic to manage instances when they are later created. Class decorator can be used to manage class object directly, instead of instance calls – to increase/modify a class with new methods. Class decorators are strongly related to function decorators, in fact, they use nearly the same syntax and very similar coding pattern but somewhere logic differs.
Note: For more information, refer to Decorators in Python
Syntactically, class decorators appear just before class statements.
@decorator class Class_Name: ... inst = Class_Name(50) This piece of code is equivalent to class Class_Name: ... Class_Name = decorator(Class_Name) inst = Class_Name(50);
Let’s understand the syntax, and how its works with an example:
In this example, the decorator rebinds the class C to another class Wrapper, which retains the original class in an enclosing scope and creates and embeds an instance (wrap) of the original class when it’s called. In more easy language,
@decorator is equivalent to
C = decorator(C) which is executed at the end of the definition of class C. In the decorator body, wrapper class modifies the class C maintaining the originality or without changing C.
cls(x) return an object of class C (with its name attribute initialized with the value of x). The method get_name return the name attribute for the wrap object. And finally in the output “Geeks” gets printed.
So, this was an overview of the decorator or wrapper for the class. The class decorators are used to add additional functionality to the class without changing the original class to use as required in any situation.
- Python | PRAW - Python Reddit API Wrapper
- self in Python class
- Inner Class in Python
- Class as decorator in python
- First Class functions in Python
- Inheritance in Python Inner Class
- How to Get a List of Class Attributes in Python?
- Python Bokeh - Colors Class
- Changing Class Members in Python
- String Template Class in Python
- How to create an empty class in Python?
- Class or Static Variables in Python
- Extend Class Method in Python
- Print objects of a class in Python
- Class and Instance Attributes in Python
- Matplotlib.patches.ConnectionPatch class in Python
- Matplotlib.patches.Circle class in Python
- Matplotlib.patches.Wedge class in Python
- Matplotlib.patches.RegularPolygon class in Python
- How to create a list of object in Python class