了解Python 的 __format__ 方法
什么是 __format__
方法?
__format__
是 Python 中的一个内置魔法方法,用于自定义对象在使用 format() 函数或 f-string(格式化字符串)时的输出格式。当你使用 format() 函数时,Python 会调用该对象的 __format__
方法来获取其格式化后的字符串表示。
示例:
value = 123.456
formatted_value = format(value, ".2f") # 保留两位小数
print(formatted_value) # 输出: 123.46
在这个示例中,Python 调用了 float 类型的 __format__
方法,生成了保留两位小数的字符串。同样的,你也可以通过实现 __format__
方法来自定义你的类的格式化输出。
format 方法的定义
在自定义类中实现 __format__
方法可以灵活定义对象的格式化逻辑。该方法的签名如下:
class MyClass:
def __format__(self, format_spec):
# 自定义格式化逻辑
return "formatted_string"
- format_spec:这是一个字符串,包含格式说明符(如宽度、对齐方式、精度等),它从 format() 函数或 f-string
中传递过来。 - 返回值:
__format__
方法应返回一个格式化后的字符串。
format 的用法
通过实现 __format__
方法,你可以灵活控制对象的字符串输出格式。以下是一个自定义类实现 __format__
方法的例子。
示例:自定义 Point 类的格式化:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __format__(self, format_spec):
if format_spec == "polar":
# 极坐标格式
r = (self.x ** 2 + self.y ** 2) ** 0.5
theta = math.atan2(self.y, self.x)
return f"({
r:.2f}, {
theta:.2f} radians)"
else:
# 默认笛卡尔坐标格式
return f"({
self.x}, {
self.y})"
# 创建 Point 对象
p = Point(3, 4)
# 使用 format() 和 f-string
print(format(p)) # 输出: (3, 4)
print(format(p, "polar")) # 输出: (5.00, 0.93 radians)