Code Explanation:
1. Defining the Decorator Function
def decorator(cls):
This defines a function named decorator.
It takes one argument cls, which will receive a class, not an object.
So this is a class decorator.
2. Adding a Method to the Class
cls.show = lambda self: "Decorated"
A new method named show is added to the class.
lambda self: "Decorated" creates a function that:
Takes self (the object calling the method)
Returns the string "Decorated"
This method becomes part of the class dynamically.
3. Returning the Modified Class
return cls
The decorator returns the modified class.
This returned class replaces the original class definition.
4. Applying the Decorator to the Class
@decorator
class Test:
pass
This is equivalent to writing:
class Test:
pass
Test = decorator(Test)
The Test class is passed to decorator.
The decorator adds the show() method to Test.
5. Creating an Object and Calling the Method
print(Test().show())
Test() creates an instance of the decorated class.
.show() calls the method added by the decorator.
The method returns "Decorated".
6. Final Output
Decorated

0 Comments:
Post a Comment