VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > python入门教程 >
  • python装饰器的4种类型:函数装饰函数、函数装饰类、类装饰函数、类装饰类

一:函数装饰函数

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))

二:函数装饰类

#Python学习交流群:778463939
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()

三:类装饰函数

#Python学习交流群:778463939
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://www.cnblogs.com/python960410445/p/13934036.html



相关教程