Python面试之装饰器的几种不同写法

废话不多说,直接撸代码

import functools
import time


# 1.普通装饰器
def logger(func):
    def wrapper(*args, **kwargs):
        print('开始处理。。。')
        func(*args, **kwargs)
        print('处理结束。')

    return wrapper


# 2.带参数的装饰器
def say_hello(who):
    def wrapper(func):
        def deco(*args, **kwargs):
            if who == "Python":
                print(f'Hello, {who}')
            elif who == "Java":
                print(f'你好,{who}')

            func(*args, **kwargs)

        return deco

    return wrapper


# 3.不带参数的类装饰器
class LoggerClass:

    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        print(f'function {self.func.__name__} is running')
        return self.func(*args, **kwargs)


# 4.带参数的类装饰器
class LoggerClassInfo:

    def __init__(self, level='info'):
        self.level = level

    def __call__(self, func):
        def wrapper(*args, **kwargs):
            print(f'[{self.level}]: function {func.__name__} is running')

            func(*args, **kwargs)

        return wrapper


# 5.偏函数和类组合实现装饰器
class DelayFunc:

    def __init__(self, duration, func):
        self.duration = duration
        self.func = func

    def __call__(self, *args, **kwargs):
        print(f'Waiting for {self.duration} seconds')
        time.sleep(self.duration)
        return self.func(*args, **kwargs)

    def eager_call(self, *args, **kwargs):
        print(f'Call without delay')
        return self.func(*args, **kwargs)


def delay(duration):
    return functools.partial(DelayFunc, duration)


# 6.装饰类的装饰器
instances = {}


def singleton(cls):
    def get_instance(*agrs, **kwargs):
        cls_name = cls.__name__
        print(f'cls_name = {cls_name}')
        if not cls_name in instances:
            print(f'add {cls_name}')
            instances[cls_name] = cls(*agrs, **kwargs)

        return instances[cls_name]

    return get_instance


@singleton
class User:

    def __init__(self, name, age):
        self.name = name
        self.age = age


@delay(2)
# @LoggerClass
# @LoggerClassInfo('debug')
# @LoggerClassInfo('info')
# @say_hello("Java")
# @say_hello("Python")
# @logger
def Test():
    print('func Test')


if __name__ == '__main__':
    Test()
    print(bool(User('小明', 20) == User('小花', 18)))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值