python装饰器

# 装饰器的基本知识
'''将函数赋值给一个变量,然后调用变量,也就调用了了该函数'''
from functools import wraps


def hi(name='小明'):
    return 'hi ' + name

print(hi())

# 函数赋值给1个变量
greet = hi
print(greet())

del hi
# print(hi())
print(greet())



# 在函数中定义函数
'''调用hello()函数,它里面的函数也都将被调用,hell()函数之外是不能访问里面的函数的'''
def hello01(name="小红"):
    print('在hello() 方法中')

    def greet():
        return '在greet()方法中'

    def welcom():
        return '在welcom()方法中'
    print(greet())
    print(welcom())
    print('返回到hello()函数中')

hello01()


# 从函数中返回函数
'''我们也可以将其作为输出返回出来,而不需要在函数里调用另一个函数'''
def hello02(name="小红"):

    def greet():
        return '在greet()方法中'

    def welcom():
        return '在welcom()方法中'

    if name == '小红':
        return greet
    else:
        return welcom

a = hello02
print(a()())


# 将函数作为参数传递给另一个函数
def hello03():
    return 'hello 小红'

def dosomethingBeforHi01(func):
    print('在hello03函数前,做一些事情')
    print(func())

dosomethingBeforHi01(hello03)

print('+++++++++++++++++++++++++++++++分隔符+++++++++++++++++++++++++++++++++')

# 第一个装饰器
'''装饰器就是在你的函数前后执行代码'''
def hello04():
    print('hello 小红')
    return 'hello 小红'

def dosomethingBeforHi02(func):
    def hello_xiaohong():
        print('在和小红打招呼前做些事情')
        print(func())
        print('在和小红打招呼后做些事情')

    return hello_xiaohong

hello04 = dosomethingBeforHi02(hello04)


hello04()

print('+++++++++++++++++++++++++++++++分隔符+++++++++++++++++++++++++++++++++')

'''@符号只是用简短的方式来生成一个被装饰器符号'''
def dosomethingBeforHi03(func):
    def hello_xiaohong():
        print('在和小红打招呼前做些事情,使用@符号')
        print(func())
        print('在和小红打招呼后做些事情,使用@符号')

    return hello_xiaohong
@dosomethingBeforHi03
def hello05():
    return 'hello 小红'

hello05()

print('+++++++++++++++++++++++++++++++分隔符+++++++++++++++++++++++++++++++++')

print(hello05.__name__)

'''装饰器函数的内部函数(hello_xiaohong)重写了我们的函数的名字和注释文档,使用functools.wraps来解决此问题'''
def dosomethingBeforHi04(func):
    @wraps(func)
    def hello_xiaohong():
        print('在和小红打招呼前做些事情,使用@符号')
        print(func())
        print('在和小红打招呼后做些事情,使用@符号')

    return hello_xiaohong
@dosomethingBeforHi04
def hello06():
    return 'hello 小红'


print(hello06.__name__)

print('+++++++++++++++++++++++++++++++分隔符+++++++++++++++++++++++++++++++++')

# 使用场景
'''登录授权'''

'''日志'''

# 带参数的装饰器
# 在函数中嵌入装饰器(包裹函数)
def logit01(logfile='out.log'):
    def logging_decorator(func):
        @wraps(func) #用它可以返回原函数的信息
        def wrapped_function(*args,**kwargs):
            log_string = func.__name__ + 'was called'
            print(log_string)
            # 打开logfile,写入内容
            with open(logfile,'a') as opened_file:
                # 将日志打到指定的logfile
                opened_file.write(log_string+'\n')
            return func(*args,**kwargs)
        return wrapped_function
    return logging_decorator


@logit01()
def myfunc1():
    pass

myfunc1()


@logit01(logfile='ds.log')
def myfunc2():
    pass

myfunc2()
print('+++++++++++++++++++++++++++++++分隔符+++++++++++++++++++++++++++++++++')

# 装饰器类
'''如果需要继承,就可使用类装饰器'''
class logit02(object):
    def __init__(self,logfile='out00002.log'):
        self.logfile = logfile

    def __call__(self, func):
        @wraps(func)
        def wrappend_function(*args,**kwargs):
            log_string = func.__name__ +'was called'
            print(log_string)
            with open(self.logfile,'a') as opened_file:
                opened_file.write(log_string+'\n')

            # 现在,发送一个通知
            self.notify()
            return func(*args,**kwargs)

        return wrappend_function

    def notify(self):
        # logit 只打日志,不做别的
        print('发送消息通知')


@logit02(logfile='哈哈哈.log')
def myfunc3():
    print('aaa')
    pass

myfunc3()


print('+++++++++++++++++++++++++++++++分隔符+++++++++++++++++++++++++++++++++')


'''创建Logit的子类,来添加email的功能'''
class email_logit(logit02):
    def __init__(self,email='aaa@.com',*args,**kwargs):
        self.email = email
        super(email_logit, self).__init__(*args,**kwargs) # 调用父类的初始化

    def notify(self):
        print('发送邮件')
        pass

@email_logit()
def myfunc4():
    print('myfunc4')
    pass

myfunc4()
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值