inherit from file and create stdout instance?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue May 15 21:43:49 EDT 2007


En Tue, 15 May 2007 20:38:14 -0300, MisterPete <pete.losangeles at gmail.com>  
escribió:

>   I could make wrappers around all of the file methods but that kind
> of defeats the purpose of inheriting from file.  It's kind of odd to
> inherit from file but then keep a file object (although then it would
> at least pass any isinstance(object, file) tests at least) and
> overwrite every single method.  I'd prefer that I inherit from file
> and just get flush and next and everything for free (and any new
> methods if they were added).

Instead of inheriting from file, you can delegate to a file instance.  
Python makes it rather easy:

py> import sys
py>
py> class Output:
...     file = None
...     verbosity = 1
...     def __init__(self, file=None, verbosity=1):
...         if file is None: file = sys.stdout
...         self.file = file
...         self.verbosity = verbosity
...     def write(self, string, messageVerbosity=1):
...         if messageVerbosity <= self.verbosity:
...             self.file.write(string)
...     def __getattr__(self, name):
...         return getattr(self.file, name)
...     def __setattr__(self, name, value):
...         if name in dir(self): self.__dict__[name] = value
...         else: setattr(self.file, name, value)
...
py> f1 = Output(verbosity=100)
py> f1.write("Console output\n")
Console output
py> f1.flush()
py> print f1.isatty()
True
py> print f1.verbosity
100
py> f1.verbosity = 5
py> print f1.verbosity
5
py>
py> f2 = Output(open("aaa.txt","w"))
py> f2.write("Goes to another file\n")
py> f2.flush()
py> print f2.isatty()
False
py> print f2.tell()
22
py> f2.close()

As you can see, I'm using file methods and attributes that I didn't  
redefine explicitely. See the section "Customizing attribute access" on  
the Python Reference Manual about __getattr__ and __setattr__

-- 
Gabriel Genellina




More information about the Python-list mailing list