164. Custom String Interpolation
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __format__(self, format_spec):
if format_spec == 'short':
return f"{self.name[0]}. ({self.age})"
return f"{self.name}, Age: {self.age}"
# Create a Person instance
person = Person("Alice", 30)
# Custom format: short version
print(f"{person:short}")
# Default format
print(f"{person}")Previous163. Using functools.partial for Function CustomizationNext165. Working with sqlite3 Database
Last updated