subclassing "file"
Peter Otten
__peter__ at web.de
Mon Jan 19 12:00:59 EST 2004
Uwe Mayer wrote:
> Hi,
>
> when extending a build in class, what does the constructor __init__(...)
> have to return?
> and how does the constructor call its base-class construtor? (or is this
> done automatically?)
>
> I want to derive from "file" to create a class that reads record from a
> binary file:
>
> class myFile(file):
> def __init__(self, filename, mode="r", bufsize=-1):
> ....?...
>
> just calling the basename and the constructor does not work:
>
>>>> f = myFile("testfile")
>>>> f
> <closed file '<uninitialized file>', mode '<uninitialized file>' at ...>
>
> What am I missing?
>
> Thanks for your comments
> Ciao
> Uwe
When you don't want to do anything in the constructor __init__(), it
suffices to override the methods of interest, e. g.:
>>> class myfile(file):
... def write(self, s):
... file.write(self, s.upper())
...
>>> f = myfile("tmp.txt", "w")
>>> f.write("a foolish consciousness")
>>> f.close()
>>> file("tmp.txt").read()
'A FOOLISH CONSCIOUSNESS'
Otherwise call base.__init__(self, someargs), e. g:
More information about the Python-list
mailing list