Trình tạo HTML
Bạn đang viết một script tạo HTML cho trang web theo thời gian thực. Hiện tại, bạn đã viết hai decorator dùng để thêm thẻ in đậm hoặc in nghiêng cho bất kỳ hàm nào trả về một chuỗi. Tuy nhiên, bạn nhận ra hai decorator này trông rất giống nhau. Thay vì viết hàng loạt decorator tương tự, bạn muốn tạo một decorator duy nhất, html(), có thể nhận bất kỳ cặp thẻ mở và thẻ đóng nào.
def bold(func):
@wraps(func)
def wrapper(*args, **kwargs):
msg = func(*args, **kwargs)
return '<b>{}</b>'.format(msg)
return wrapper
def italics(func):
@wraps(func)
def wrapper(*args, **kwargs):
msg = func(*args, **kwargs)
return '<i>{}</i>'.format(msg)
return wrapper
Bài tập này là một phần của khóa học
Viết hàm trong Python
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
def html(open_tag, close_tag):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
msg = func(*args, **kwargs)
return '{}{}{}'.format(open_tag, msg, close_tag)
# Return the decorated function
return ____
# Return the decorator
return ____