Make an object a "character buffer object"
I have a custom class, which has s开发者_运维百科ome string data. I wish to be able to save this string data to a file, using a file handle's write object. I have implemented __str__()
, so i can do str(myobject)
, what is the equivalent method for making python consider my object to be a character buffer object?
If you are trying to use your object with library code, that expects to be able to write what you give it to a file, then you may have to resort to implementing a "duck file" class that acts like a file
but supports your stringable object. Unfortunately, file
is not a type that you can subclass easily, at least as of Python 2.6. You will have to implement enough of the file protocol (write
, writelines
, tell
, etc.) to allow the library code to work as expected.
There isn't a single function, but a whole range of them - read
, seek
, etc.
Why don't you subclass StringIO.StringIO
, which is already a string buffer?
精彩评论