python decorator 之函数装饰类

python decorator 函数装饰类

函数装饰类,在每次类实例化对象之前调用:

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('fun self.a =', self.a)

    def fun2(self):
        print('fun2 self.a = ', self.a)


obj1 = Foo('object 1')
obj1.fun()
obj1.fun2()

print()
obj2 = Foo('object 2')
obj2.fun()
obj2.fun2()

output:

class name: Foo
fun self.a =  object 1
fun2 self.a =  object 1

class name: Foo
fun self.a =  object 2
fun2 self.a =  object 2

发布了134 篇原创文章 · 获赞 20 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/u011583798/article/details/87802473