
Class Decorators
def add_attribute(cls):
cls.new_attribute = "New attribute added by decorator"
return cls
@add_attribute
class MyClass():
pass
# Areate an instance of MyClass
obj = MyClass()
# Access the new attribute
print(obj.new_attribute) # Output: New attribute added by decoratordef double_results(cls):
# iterate over all attributes
for attr_name, attr_value in cls.__dict__.items():
if callable(attr_value): # if the attribute is a method
setattr(cls, attr_name, double_decorator(attr_value))
return cls
def double_decorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs) * 10
return wrapper
@double_results
class MyClass:
def add(self, a, b):
return a + b
# create an instance of MyClass
obj = MyClass()
# call the 'add' method
print(obj.add(2, 2)) # Output: 40Decorator Class
範例 – 帶參數的 Decorator Class
範例 – Decorator Class 實例
PEP 614
參考資料
Last updated