常见或 pythonic __repr__ 方法
Common or pythonic __repr__ methods
我通常会写一个 __repr__
来展示如何首先重新创建实例。例如:
class Component:
def __init__(self, start, end):
self.start = start
self.end = end
def __repr__(self):
return f'{self.__class__.__name__}(start={self.start}, end={self.end})'
是否有 'standard' 的写法 __repr__
,如果没有,是否有建议 options/best-practices 应该如何写,或者它完全是主观的?
一般规则是,如果可能的话,produce output that could be typed to recreate the object; from the docs:
If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned.
该规则的第二部分主要是为了确保您不会制作看起来像规范的重新制作的东西;在实践中,我没有看到它被虔诚地遵循。
对于您的具体情况,我只推荐两个调整:
- 如果
Component
可能包含另一个 Component
作为 start
或 end
值,请用 reprlib.recursive_repr
修饰 __repr__
以避免在 Component
包含自身的情况下无限递归的可能性(对于图书馆很重要,无论图书馆作者的意图如何,这都可能发生)
明确地使用你属性的 repr
和 !r
修饰符(你不需要 "human friendly" 字符串,你想要一个表示),改变字符串到:
return f'{self.__class__.__name__}(start={self.start!r}, end={self.end!r})'
我通常会写一个 __repr__
来展示如何首先重新创建实例。例如:
class Component:
def __init__(self, start, end):
self.start = start
self.end = end
def __repr__(self):
return f'{self.__class__.__name__}(start={self.start}, end={self.end})'
是否有 'standard' 的写法 __repr__
,如果没有,是否有建议 options/best-practices 应该如何写,或者它完全是主观的?
一般规则是,如果可能的话,produce output that could be typed to recreate the object; from the docs:
If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned.
该规则的第二部分主要是为了确保您不会制作看起来像规范的重新制作的东西;在实践中,我没有看到它被虔诚地遵循。
对于您的具体情况,我只推荐两个调整:
- 如果
Component
可能包含另一个Component
作为start
或end
值,请用reprlib.recursive_repr
修饰__repr__
以避免在Component
包含自身的情况下无限递归的可能性(对于图书馆很重要,无论图书馆作者的意图如何,这都可能发生) 明确地使用你属性的
repr
和!r
修饰符(你不需要 "human friendly" 字符串,你想要一个表示),改变字符串到:return f'{self.__class__.__name__}(start={self.start!r}, end={self.end!r})'