Wrapper class in Python

In this tutorial, you are going to learn about the Wrapper class in Python with example. Continue following this article…

What is a Wrapper Class?

A Wrapper class is used to organize codes after creating classes with wrapper logic to organize instances that are created later in the program.

These classes are used to add additional features to the class without changing the original class.

An example of Wrapper Class with Python code example is given below:

def WrapperExample(A): 
    class Wrapper: 
        def __init__(self, y): 
            self.wrap = A(y) 
        def get_number(self): 
            return self.wrap.name 
    return Wrapper 
class code: 
    def __init__(self, z): 
        self.name = z 
y = code("Wrapper class") 


We will see the output will print the result you can see below:

Wrapper class

Program Explanation:

Now let’s see what we did in our program step by step.

First, we create one function which is named as a wrapper Example. Next, create class Wrapper and two functions i.e __init__ and get_name. The function __init__ is used to initialize the function. HereĀ  A(y) returns an object to class code. The decorator rebinds that class code to another class Wrapper that retains the original class in the enclosing scope and then creates and embeds an instance of the original class when it is called.

Next, we use a decorator which is a design pattern in python used to add additional functionality without changing the structure of a program. @decorator is equivalent to code=decorator(code) which is executed at the end of the class.

The function get_name returns the name attribute for the wrapped object and gives the output as “Wrapper class”.

This is an explanation about the Wrapper class in Python.

Leave a Reply