实现说明
活动部件是类 Point、OnlyRepr、OnlyStr和函数 __init__、__repr__、__str__。
使用要点
- 演示输出是带标签的(
repr falls back to default:),每个操作都会留下自己的一行标注。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 __init__、__repr__、__str__。
签名一览:def __init__(self, x, y)
核心语句
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return "repr form"
代码示例
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
# __repr__ targets developers: unambiguous, ideally re-constructible
def __repr__(self):
return f"Point({self.x}, {self.y})"
# __str__ targets end users: readable, even if it loses information
def __str__(self):
return f"({self.x}, {self.y})"
point = Point(3, 4)
print(str(point))
print(repr(point))
print(point) # print uses __str__ when available
# Containers render their items with repr only — __str__ never runs there
print([point, point])
# str() falls back to __repr__ when __str__ is missing
class OnlyRepr:
def __repr__(self):
return "repr form"
print(str(OnlyRepr()) == "repr form")
# With only __str__, repr() uses the default object repr, not your string
class OnlyStr:
def __str__(self):
return "str form"
print("repr falls back to default:", "OnlyStr object" in repr(OnlyStr()))