可以用f-string打印自定义对象。默认设置是,如果向f-string表达式传递了一个对象,它将会显示该对象 str 方法的返回值。不过,也可以用显式转换操作标志来打印repr的值。
● !r - 使用 repr() 将值转化为文本.
● !s - 使用 str() 将值转化为文本.
>>> class Color:
def __init__(self, r: float = 255, g: float = 255, b: float = 255):
self.r = r
self.g = g
self.b = b
def __str__(self) -> str:
return "A RGB color"
def __repr__(self) -> str:
return f"Color(r={self.r}, g={self.g}, b={self.b})"
>>> c = Color(r=123, g=32, b=255)
# 如不加任何操作符, 会打印 __str__ 的值
>>> f"{c}"
'A RGB color'
# 用`obj!r` 的话会打印 __repr__ 的值
>>> f"{c!r}"
'Color(r=123, g=32, b=255)'
# 使用!s跟默认值一样
>>> f"{c!s}"
'A RGB color'
Python也允许通过定义不同类型使用format方法控制格式化结果,下面的例子会展示所有可能情况。
>>> class Color:
def __init__(self, r: float = 255, g: float = 255, b: float = 255):
self.r = r
self.g = g
self.b = b
def __str__(self) -> str:
return "A RGB color"
def __repr__(self) -> str:
return f"Color(r={self.r}, g={self.g}, b={self.b})"
>>> c = Color(r=123, g=32, b=255)
# When no option is passed, the __str__ result is printed
>>> f"{c}"
'A RGB color'
# When `obj!r` is used, the __repr__ output is printed
>>> f"{c!r}"
'Color(r=123, g=32, b=255)'
# Same as the default
>>> f"{c!s}"
'A RGB color'
Python also allows us to control the formatting on a per-type basis through the __format__ method. The following example shows how you can do all of that.
>>> class Color:
def __init__(self, r: float = 255, g: float = 255, b: float = 255):
self.r = r
self.g = g
self.b = b
def __str__(self) -> str:
return "A RGB color"
def __repr__(self) -> str:
return f"Color(r={self.r}, g={self.g}, b={self.b})"
def __format__(self, format_spec: str) -> str:
if not format_spec or format_spec == "s":
return str(self)
if format_spec == "r":
return repr(self)
if format_spec == "v":
return f"Color(r={self.r}, g={self.g}, b={self.b}) - A nice RGB thing."
if format_spec == "vv":
return (
f"Color(r={self.r}, g={self.g}, b={self.b}) "
f"- A more verbose nice RGB thing."
)
if format_spec == "vvv":
return (
f"Color(r={self.r}, g={self.g}, b={self.b}) "
f"- A SUPER verbose nice RGB thing."
)
raise ValueError(
f"Unknown format code '{format_spec}' " "for object of type 'Color'"
)
>>> c = Color(r=123, g=32, b=255)
>>> f'{c:v}'
'Color(r=123, g=32, b=255) - A nice RGB thing.'
>>> f'{c:vv}'
'Color(r=123, g=32, b=255) - A more verbose nice RGB thing.'
>>> f'{c:vvv}'
'Color(r=123, g=32, b=255) - A SUPER verbose nice RGB thing.'
>>> f'{c}'
'A RGB color'
>>> f'{c:s}'
'A RGB color'
>>> f'{c:r}'
'Color(r=123, g=32, b=255)'
>>> f'{c:j}'
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-20-1c0ee8dd74be> in <module>
----> 1 f'{c:j}'
<ipython-input-15-985c4992e957> in __format__(self, format_spec)
29 f"- A SUPER verbose nice RGB thing."
30 )
---> 31 raise ValueError(
32 f"Unknown format code '{format_spec}' " "for object of type 'Color'"
33 )
ValueError: Unknown format code 'j' for object of type 'Color'
最后,还有个用来转义ASCII字符的a操作符。更多信息可参考:
docs.python.org/3/library/functions.html#as..
>>> utf_str = "Áeiöu"
>>> f"{utf_str!a}"
"'\\xc1ei\\xf6u'"