python装饰器的4种类型:函数装饰函数、函数装饰类、类装饰函数、类装饰类

摘自:https://blog.csdn.net/gezailushang/article/details/84291092 

https://blog.csdn.net/xiemanr/article/details/72510885

 

一:函数装饰函数

  1. def wrapFun(func):
  2. def inner(a, b):
  3. print('function name:', func.__name__)
  4. r = func(a, b)
  5. return r
  6. return inner
  7. @wrapFun
  8. def myadd(a, b):
  9. return a + b
  10. print(myadd(2, 3))

二:函数装饰类

  1. def wrapClass(cls):
  2. def inner(a):
  3. print('class name:', cls.__name__)
  4. return cls(a)
  5. return inner
  6. @wrapClass
  7. class Foo():
  8. def __init__(self, a):
  9. self.a = a
  10. def fun(self):
  11. print('self.a =', self.a)
  12. m = Foo('xiemanR')
  13. m.fun()

三:类装饰函数

  1. class ShowFunName():
  2. def __init__(self, func):
  3. self._func = func
  4. def __call__(self, a):
  5. print('function name:', self._func.__name__)
  6. return self._func(a)
  7. @ShowFunName
  8. def Bar(a):
  9. return a
  10. print(Bar('xiemanR'))

四:类装饰类

  1. class ShowClassName(object):
  2. def __init__(self, cls):
  3. self._cls = cls
  4. def __call__(self, a):
  5. print('class name:', self._cls.__name__)
  6. return self._cls(a)
  7. @ShowClassName
  8. class Foobar(object):
  9. def __init__(self, a):
  10. self.value = a
  11. def fun(self):
  12. print(self.value)
  13. a = Foobar('xiemanR')
  14. a.fun()

 

posted @ 2020-01-10 00:16  LiuYanYGZ  阅读(815)  评论(0编辑  收藏  举报