函数装饰类
def wrapClass(cls):
def inner(a):
print('class name:', cls.__name__)
return cls(a)
return inner
@wrapClass
class Foo():
def __new__(cls,a):
print("__new__方法被执行")
return super().__new__(cls)
def __init__(self,a):
print("__init__方法被执行")
m = Foo('peter')
# 输出
# class name: Foo
# __new__方法被执行
# __init__方法被执行
类装饰函数
class WrapClass():
def __init__(self, func):
self._func = func
def __call__(self, parm):
print('function name:', self._func.__name__)
return self._func(parm)
@WrapClass
def Foo(parm):
print(parm)
Foo('parm')
# 输出
# function name: Foo
# parm
类装饰类
class WrapClass(object):
def __init__(self, cls):
self._cls = cls
def __call__(self, parm):
print('class name:', self._cls.__name__)
return self._cls(parm)
@WrapClass
class Foo(object):
def __init__(self, parm):
self.value = parm
print(self.value)
f = Foo('parm')
# 输出
# class name: Foo
# parm