如何使用装饰器来定义函数的默认参数?
def my_function(name, age=25):
# Some function logic
return "Hello, {}!".format(name)
# Without decorator
print(my_function("John"))
# With decorator
@decorator
def my_function(name, age=25):
return "Hello, {}!".format(name)
# Output:
# Hello, John!
Explanation:
- The
@decorator
decorator is used to wrap themy_function
function. - The
age
parameter is set to a default value of 25. - When the function is called without any arguments, the
age
parameter will automatically be set to 25. - The
decorator
allows you to define custom behavior for the decorated function, such as logging or modifying the function signature.
Benefits of using a decorator:
- Code reusability: You can define the default parameter values once and use them in multiple functions.
- Flexibility: You can customize the behavior of the function without modifying the function itself.
- Logging: You can easily add logging statements to the decorated function.
Note:
- Decorators are called before the function is executed.
- The default parameter value can be any Python data type, including functions.
- You can use multiple decorators on the same function.