Code Explanation:
๐น 1. Defining the Decorator Function
def deco(cls):
✅ Explanation
A function named deco is created.
It accepts one argument named cls.
Here, cls represents a class object, not a normal variable.
Think of it like this:
Class
↓
Decorator Function
↓
Modify Class
↓
Return Class
Nothing executes yet.
๐น 2. Adding a New Class Attribute
cls.value = 100
✅ Explanation
This line adds a new class variable named value.
Initially, the class has no attributes.
Before:
Test
↓
(No attributes)
After this line executes:
Test
↓
value = 100
This attribute belongs to the class, so every object of this class can access it.
๐น 3. Returning the Modified Class
return cls
✅ Explanation
After modifying the class, the decorator returns it.
Think of it like:
Receive Class
↓
Modify It
↓
Return Updated Class
If you don't return the class, Python would replace the class with None.
๐น 4. Applying the Decorator
@deco
✅ Explanation
This line tells Python:
After creating the class,
send it to
deco()
Python internally converts:
@deco
class Test:
pass
into:
class Test:
pass
Test = deco(Test)
This is the most important concept of decorators.
๐น 5. Creating the Class
class Test:
✅ Explanation
Python creates the Test class.
Initially:
Test
↓
Empty Class
It only contains the default attributes provided by Python.
๐น 6. The pass Statement
pass
✅ Explanation
pass means:
Do Nothing
The class has no methods and no variables.
It simply acts as an empty placeholder.
๐น 7. Python Calls the Decorator Automatically
After the class is created, Python automatically executes:
Test = deco(Test)
✅ Explanation
Execution flow:
Create Test Class
↓
Call deco(Test)
↓
Add value = 100
↓
Return Test
↓
Store Back in Test
Now the class becomes:
Test
│
└── value = 100
๐น 8. Accessing the Class Variable
Test.value
✅ Explanation
Python searches for value inside the class.
Current class:
Test
↓
value = 100
Value found:
100
๐น 9. Printing the Value
print(Test.value)
✅ Explanation
Python prints the class variable.
Output:
100
๐ฏ Final Output
100

0 Comments:
Post a Comment