python给类写装饰器
时间: 2023-07-18 19:47:41 浏览: 50
Python 中可以使用装饰器为类添加额外的功能或修改类的行为。类装饰器可以在类定义前使用 `@` 符号来装饰类,例如:
```python
def my_decorator(cls):
class NewClass(cls):
def new_method(self):
print("This is a new method added by the decorator.")
return NewClass
@my_decorator
class MyClass:
def existing_method(self):
print("This is an existing method of the class.")
my_object = MyClass()
my_object.existing_method() # This is an existing method of the class.
my_object.new_method() # This is a new method added by the decorator.
```
以上代码定义了一个名为 `my_decorator` 的装饰器函数,接受一个类作为参数,并返回一个新的类。新的类继承了原来的类,并添加了一个新的方法 `new_method`。
然后,使用 `@my_decorator` 装饰 `MyClass` 类,将 `MyClass` 类传递给 `my_decorator` 函数,生成一个新的类 `NewClass`。
最后,创建一个 `MyClass` 的实例,并调用 `existing_method` 和 `new_method` 方法,验证装饰器的效果。
类装饰器的使用方法与函数装饰器类似,可以使用类装饰器为类添加新的方法、属性或修改类的行为。