I have defined the __str__ and __repr__ in my class foo
When I print foo(), it works just fine.
Of course, redefining stdout as a file object and calling print foo() would write the string representation to the file, but is that the most pythonic way to do it?
Simply call str or repr on the object, like this:
with open('somefile.txt', 'w') as f:
f.write(repr(foo()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With