装饰器的一些使用方法

装饰器的一些使用方法

在类中写装饰器

方式一:

class Foo:
    def __init__(self):
        self.name = 'CharmNight'

    def inners(funcs):
        def inner(self, *args, **kwargs):
            ret = funcs(self, *args, **kwargs)
            print(self.name)
            return ret
        return inner

    @inners
    def func(self):
        print('0101')
        return 'over'

f = Foo()
print(f.func())

方式二:

class Demo:

    @staticmethod
    def demo(func):
        def inner(*args, **kwargs):
            ret = func(*args, **kwargs)
            return ret
        return inner

class D4:

    @Demo.demo
    def asd(self):
        print('asd')

d4 = D4()
d4.asd()

方式三:

class Demo:
    def __init__(self, func):
        self.func = func
        self.name = 'CharmNight'

    def __call__(self, *args, **kwargs):
        res = self.func(*args, **kwargs)
        print(self.name)
        return res


@Demo
def func():
    print('0101')
    return 'over'

print(func())

进阶版

import time

class Demo:
    def __init__(self):
        self.name = 'CharmNight'

    def set_name(self, func):
        print(self.name)
        return func

    def get_run_time(self, func):
        def inner(*args, **kwargs):
            start = time.time()
            ret = func(*args, **kwargs)
            print(time.time() - start)
            return ret
        return inner


demo = Demo()


@demo.set_name
def func():
    print('0001')
    return 'over'


@demo.get_run_time
def func2():
    print('0002')
    time.sleep(1)
    return 'over'


print(func())
print(func2())

你可能感兴趣的:(python_学习)