Py3K: file inheritance

Yosifov Pavel bulg at ngs.ru
Fri Oct 21 00:17:41 EDT 2011


On 21 окт, 00:42, Ian Kelly <ian.g.ke... at gmail.com> wrote:
> On Thu, Oct 20, 2011 at 11:28 AM, Yosifov Pavel <b... at ngs.ru> wrote:
> > In the Python 2.x was simple to create own file object:
>
> > class MyFile(file):
> > špass
>
> > for example to reimplement write() or something else. How to do it in
> > Python 3.x?
>
> See the docs for the io module.  Depending on what you want to do, you
> probably need to subclass either io.FileIO or io.TextIOWrapper.

Little silly example:

class MyFile(file):
  def __init__(self, *a, **ka):
    super(MyFile, self).__init__(*a, **ka)
    self.commented = 0
  def write(self, s):
    if s.startswith("#"):
      self.commented += 1
      super(MyFile, self).write(s)

When I tried in Python 3.x to inherit FileIO or TextIOWrapper and then
to use MyFile (ex., open(name, mode, encoding), write(s)...) I get
errors like 'unsupported write' or AttributeError 'readable'... Can
you show me similar simple example like above but in Python 3.x?



More information about the Python-list mailing list