Wrapper Class in Python
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course