深度阅读

How to Write a decorator to add a '$' sign to a number in Python

作者
作者
2023年08月22日
更新时间
10.1 分钟
阅读时间
0
阅读量

Certainly, here’s an example of a Python decorator that adds a ‘$’ sign to a number:

def add_dollar_sign(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return f'${result}'
    return wrapper

You can then apply this decorator to any function that returns a number, and it will add the ‘$’ sign to the result. For example:

@add_dollar_sign
def calculate_total_cost(price, quantity):
    return price * quantity

total_cost = calculate_total_cost(10, 5)
print(total_cost) # outputs "$50"

In this example, the add_dollar_sign decorator takes a function as an argument, defines a new function wrapper that calls the original function and adds a ‘$’ sign to the result, and finally returns the new function. The @add_dollar_sign syntax applies the decorator to the calculate_total_cost function, so that when it is called the result is automatically wrapped with the ‘$’ sign.

I hope this helps! Let me know if you have any more questions.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。