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