Decorators are Pythonic functions that enhance other functions. We'll create two decorators, @make_bold and @make_italic, to format text in bold and italics. Here's how:
</p> <h1>Decorator to make text bold</h1> <p>def make_bold(func):</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">def wrapper(): return "<b>" + func() + "</b>" # Surround the result with bold tags return wrapper
def make_italic(func):
def wrapper(): return "<i>" + func() + "</i>" # Surround the result with italic tags return wrapper
@make_bold
@make_italic
def say():
return "Hello"
print(say()) # Output: "Hello"
You can also create decorators that accept arguments. For example, let's make a decorator that adds a timestamp to the result:
<br>import time</p> <h1>Decorator to add a timestamp to a function</h1> <p>def add_timestamp(func):</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">def wrapper(*args, **kwargs): timestamp = time.ctime() # Get the current time return f"{timestamp}: {func(*args, **kwargs)}" # Prepend the timestamp to the call return wrapper
@add_timestamp
def greet(name):
return f"Hello, {name}!"
print(greet("John")) # Output: "2023-01-01 12:00:00: Hello, John!"
Decorators work not only for functions but also for methods. Here's how to decorate a method:
<br>class User:</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">def __init__(self, name): self.name = name
def capitalize_name(method):
def wrapper(self): return method(self).capitalize() # Capitalize the result return wrapper
@capitalize_name
def get_name(self):
return self.name
user = User("john")
print(user.get_name()) # Output: "John"
The above is the detailed content of How Can I Use Python Decorators to Make Functions Bold and Italic, Add Timestamps, and Capitalize Method Results?. For more information, please follow other related articles on the PHP Chinese website!