Thursday, December 26, 2024
Google search engine
HomeLanguagesWrapper Class in Python

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

Syntax:
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:

Example:




# decorator accepts a class as 
# a parameter
def decorator(cls):
      
    class Wrapper:
          
        def __init__(self, x):
              
            self.wrap = cls(x)
              
        def get_name(self):
              
            # fetches the name attribute
            return self.wrap.name
          
    return Wrapper
  
@decorator
class C:
    def __init__(self, y):
        self.name = y
  
# its equivalent to saying
# C = decorator(C)
x = C("Geeks")
print(x.get_name())   


OUTPUT:

Geeks

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.

RELATED ARTICLES

Most Popular

Recent Comments