python-装饰器(77)

# 转自https://www.jianshu.com/c/00c61372c46a网址
def color(func):
    def red():
        return '\033[31;1m%s\033[0m' % func()
    return red

def hello():
    return 'Hello Word!'

@color
def welcome():
    return 'Hello China!'

if __name__ == '__main__':
    hello = color(hello)
    print(hello())
    print(welcome())







#带有参数的装饰器
def color(func):
    def red(*args):
        return '\033[31;1m%s\033[0m' % func(*args)
    return red

@color
def hello(word):
    return "Hello %s" % word

@color
def welcome():
    return "How are you?"

if __name__ == '__main__':
    print(hello('China'))
    print(welcome())






#返回不同颜色的字体
def colors(c):
    def set_color(func):
        def red(*word):
            return '\033[31;1m%s\033[0m' % func(*word)
        def green(*word):
            return '\033[32;1m%s\033[0m' % func(*word)
        adict = {'red': red, 'green': green}
        return adict[c]
    return set_color

@colors('red')
def hello():
    return 'Hello world!'

@colors('green')
def welcome(word):
    return 'Hello %s' % word

if __name__ == '__main__':
    print(hello())   # -> hello = set_color(hello)
    print(welcome('China'))



你可能感兴趣的:(python)