Skip to main content
 首页 » 编程设计

python之将类实例的字符串表示写入文件

2025年05月04日23lexus

我已经在我的class foo
中定义了__str__ 和__repr__ 当我 print foo() 时,它工作正常。
当然,将 stdout 重新定义为 file 对象并调用 print foo() 会将字符串表示形式写入文件,但这是最符合 Python 风格的方法吗?< br/>

请您参考如下方法:

只需调用 str或 repr在对象上,像这样:

with open('somefile.txt', 'w') as f: 
    f.write(repr(foo()))