Py3K: file inheritance

Yosifov Pavel bulg at ngs.ru
Fri Oct 21 08:36:28 EDT 2011


On 21 окт, 13:50, Ian Kelly <ian.g.ke... at gmail.com> wrote:
> On Thu, Oct 20, 2011 at 10:17 PM, Yosifov Pavel <b... at ngs.ru> wrote:
> > 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?
>
> class MyTextIO(io.TextIOWrapper):
>     def __init__(self, *args, **kw):
>         super().__init__(*args, **kw)
>         self.commented = 0
>     def write(self, s):
>         if s.startswith('#'):
>             self.commented += 1
>             super().write(s)
>
> buffered = open(name, 'wb')
> textio = MyTextIO(buffered, encoding='utf-8')
> textio.write('line 1')
> textio.write('# line 2')
> textio.close()
> print(textio.commented)
>
> HTH,
> Ian

Thank you very much!



More information about the Python-list mailing list