百万年薪python之路 -- 装饰器进阶

假如想象 提交于 2019-11-30 12:32:15

本文链接:https://blog.csdn.net/xiemanR/article/details/72510885

一:函数装饰函数

def wrapFun(func):
    def inner(a, b):
        print('function name:', func.__name__)
        r = func(a, b)
        return r
    return inner
 
@wrapFun
def myadd(a, b):
    return a + b
 
print(myadd(2, 3))

二:函数装饰类

def wrapClass(cls):
    def inner(a):
        print('class name:', cls.__name__)
        return cls(a)
    return inner
 
@wrapClass
class Foo():
    def __init__(self, a):
        self.a = a
 
    def fun(self):
        print('self.a =', self.a)
 
 
m = Foo('xiemanR')
m.fun()

三:类装饰函数

class ShowFunName():
    def __init__(self, func):
        self._func = func
 
    def __call__(self, a):
        print('function name:', self._func.__name__)
        return self._func(a)
 
 
@ShowFunName
def Bar(a):
    return a
 
print(Bar('xiemanR'))

四:类装饰类

class ShowClassName(object):
    def __init__(self, cls):
        self._cls = cls
 
    def __call__(self, a):
        print('class name:', self._cls.__name__)
        return self._cls(a)
 
 
@ShowClassName
class Foobar(object):
    def __init__(self, a):
        self.value = a
 
    def fun(self):
        print(self.value)
 
a = Foobar('xiemanR')
a.fun()

更加详细补充: https://blog.csdn.net/five3/article/details/83447467

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!