Skip to main content
 首页 » 编程设计

python之哪个更 Pythonic 调用 __str__() 方法或转换为 str()

2025年05月04日16jyk

我有一个字典对象的包装器类,我很好奇在我的类中实现 __repr__ 方法时是否优先选择另一个:

class MyClass(object): 
  def __init__(self): 
    self._obj = dict() 
  def __repr__(self): 
    return self._obj.__str__() 

或

class MyClass(object): 
  def __init__(self): 
    self._obj = dict() 
  def __repr__(self): 
    return str(self._obj) 

str() 的第二个实现对我来说很合适。我只是想确保我没有遗漏任何东西。

请您参考如下方法:

你是对的。您应该避免直接调用双下划线方法:内置函数是执行此操作的 Pythonic 方式。

(同样适用于 len(foo) 与 foo.__len__() 的示例。)