将类实例的字符串表示形式写入文件

Lel*_*uge 4 python file-io class

我已经在我的 When I中定义了__str__and ,它工作得很好。 当然,将 stdout 重新定义为对象并调用会将字符串表示形式写入文件,但这是最 Pythonic 的方法吗?__repr__class foo
print foo()
fileprint foo()

phi*_*hag 5

只需在对象上调用stror即可,如下所示:repr

with open('somefile.txt', 'w') as f:
    f.write(repr(foo()))
Run Code Online (Sandbox Code Playgroud)