关于python: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://www.cnblogs.com/serpe…
https://www.cnblogs.com/liany…

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理