class MyDerector: # 将类作为装饰器
def __init__(self,f):
self.f = f
def __call__(self, *args, **kwargs):
print("first--")
result = self.f(*args, **kwargs)
print("second--")
return result
class ParmaDerector: # 带参数传递的类作为装饰器
def __init__(self,name):
self.name = name
def __call__(self, f):
def wrap(*args):
print(f"first--{self.name}")
result = f(*args)
print("second--")
return result
return wrap
@ParmaDerector("JAck")
def myfun():
print("hello world!")
return 200
print(myfun())
def cls_decorator(cls): # 类的装饰器
print("cls decorator")
def inner():
print("start")
obj = cls()
print("end")
return obj
return inner
# 类的装饰器
@cls_decorator
class Person:
pass
p1 = Person()
p2 = Person()
python 类和装饰器
最新推荐文章于 2024-07-13 21:34:41 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)