使用python中的装饰器更改文本颜色

问题描述 投票:0回答:1

我在理解装饰器语法时遇到问题。我可以证明我在学校完成的任务。

“给出端子的颜色开关转义码”

GREEN = "\033[32m"
RED = "\033[31m"
RESET = "\033[00m"
print (GREEN + "yes", RED + "no", RESET + 'maybe')

class Color:
    def __init__(self, color):
        self.color = color

    def __enter__(self):
        print(self.color)

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(RESET, end='')


# Verify that you get color output

with Color(RED):
    print('Red day')

with Color(GREEN):
    print('Green forest')

“使用修饰符重复此功能,以验证以下内容:”

@print_in_red
def hello():
    print("Hello world!")

hello()

我必须定义一个函数,但是在这种情况下我不明白如何构建它,我对装饰器的语法也有些困惑。在课程中,老师在函数内部使用了一个函数,称为“包装器”,并使用了args,kwargs,我不知道是否要构建2个函数,因为任务很简单。

def print_in_red(f):
         ???
    return ???

请不要将此问题与其他长期无关的讨论联系起来。我知道有些问题对于专业程序员来说是多余的,但是对于初学者来说,即使两个任务非常相似,也很难将它们联系起来。否则,您会敦促初学者离开此网站。谢谢!

python python-3.x python-decorators
1个回答
0
投票

听起来像您的老师说的对。

装饰器将一个函数转换为另一个函数,并将原始函数作为参数传递。

通常,您要在该新函数中执行的操作是调用原始函数,但围绕它执行其他操作。

因此,我们有一个简单的装饰器print_result,它调用一个函数,然后在返回结果之前先打印结果。

我们去:

def print_result(old_function):
  # create a new function that's valid only in this scope.
  def new_function(*args, **kwargs):  # args and kwargs mimic any arguments and keyword arguments that the old function would have.
    ret = old_function(*args, **kwargs)
    print ret
    return ret
  return new_function

因此,在您的情况下,您希望在函数周围使用红色,而不是接收响应并进行打印。

希望这可以帮助您充分理解作业,而无需完成所有工作。

© www.soinside.com 2019 - 2024. All rights reserved.