Step by Step Explanation:
def decorator(cls):
cls.value = 42 # Adds a new attribute `value` to the class
return cls # Returns the modified class
Step 1: Define a Class Decorator
def decorator(cls):
This defines a function named decorator that takes a class (cls) as its parameter.
When applied, it will modify the class by adding new attributes or methods.
cls.value = 42
This adds a new attribute value to the class passed to the decorator.
Every class that uses @decorator will automatically have value = 42.
return cls
The modified class is returned.
This ensures that the original class remains functional but now has additional modifications.
@decorator # Applying the decorator to the class
class Test:
pass
Step 2: Apply the Decorator
@decorator
This applies the decorator function to the Test class.
Equivalent to manually writing:
class Test:
pass
Test = decorator(Test) # Modifies `Test` by adding `value = 42`When Test is passed into decorator(), it modifies Test by adding value = 42.
print(Test.value) # Accessing the modified class attribute
Step 3: Print the New Attribute
Test.value
Since the decorator added value = 42, this now exists in the class.
print(Test.value) prints 42.
0 Comments:
Post a Comment