Noob Q: subclassing or wrapping file class

kj no.email at please.post
Wed Sep 16 19:06:18 EDT 2009


In <pan.2009年09月16日.22.09.59 at REMOVE.THIS.cybersource.com.au> Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes:
>On 2009年9月16日 21:56:09 +0000, kj wrote:

>...
>> I thought at first that I could achieve this by overriding __getattr__:
>>>> def __getattr__(self, attribute):
>> return self.fh.__getattr__(attribute)
>>>> But to my surprise this did not work too well. For example, if I use a
>> GzipFile object as the argument to MyFile, the iterator of the resulting
>> object works as expected, but if I attempt to access its closed
>> attribute I get the error
>>>> AttributeError: GzipFile instance has no attribute '__getattr__'
>>>> And it doesn't have __getattribute__ either. (And here I'd been
>> thinking that __getattr__ and __getattribute__ were pretty much
>> universal... Clearly not!)
>>>> Is there a standard idiom that I'm missing for doing this sort of thing?

>Instead of:

>x.__getattr__('name')

>write this:

>getattr(x, 'name')

This did the trick.
>Also, do a search for "automatic delegation python", or just look at Alex 
>Martelli's cookbook recipe:

>http://code.activestate.com/recipes/52295/

That was instructive. Thanks!
kj


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /