Python带参数的函数装饰器


 

 

# -*- coding: utf-8 -*-
# author:baoshan
# 带参数的函数装饰器


def say_hello(country):
    def wrapper(func):
        def deco(*args, **kwargs):
            if country == 'china':
                print('你好!')
            elif country == 'america':
                print('hello')
            else:
                return
            func(*args, **kwargs)
        return deco
    return wrapper


@say_hello('china')
def chinese():
    print('我来自中国。')


@say_hello('america')
def america():
    print('I am from America.')


america()
print('-'*20)
chinese()

 

输出结果:

hello
I am from America.
--------------------
你好!
我来自中国。

 

带参数的函数装饰器

参考自:https://zhuanlan.zhihu.com/p/65968462

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM