CodesCompiler
๐Ÿ”
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact ๐Ÿš€ Get Started Free

PYTHON - Wrapper Classes

Python - Wrapper Classes

Afunctionin Python is a first-order object. A function can have another function as its argument and wrap another function definition inside it. This helps in modifying a function without actually changing it. Such functions are calleddecorators.

This feature is also available forwrapping a class. This technique is used to manage the class after it is instantiated by wrapping its logic inside a decorator.

Example

PYTHON CODE
def decorator_function(Wrapped):
   class Wrapper:
      def __init__(self,x):
         self.wrap = Wrapped(x)
      def print_name(self):
         return self.wrap.name
   return Wrapper
   
@decorator_function
class Wrapped:
   def __init__(self,x):
      self.name = x
      
obj = Wrapped('CodesCompiler')
print(obj.print_name())

Here,Wrappedis the name of the class to be wrapped. It is passed as argument to a function. Inside the function, we have aWrapper class, modify its behavior with theattributesof the passed class, and return the modified class. The returned class is instantiated and itsmethodcan now be called.

When you execute this code, it will produce the followingoutputโˆ’

PYTHON CODE
CodesCompiler