mixin helper class for unknown attribute access?

Alex Hunsley lard at tardis.ed.ac.molar.uk
Mon Oct 31 07:47:16 EST 2005


Steven D'Aprano wrote:
> On Mon, 31 Oct 2005 10:39:40 +0000, Alex Hunsley wrote:
> 
> 
>>I know that I can catch access to unknown attributes with code something 
>>like the following:
>>
>>class example:
>>      def __getattr__(self, name):
>>          if name == 'age':
>>              return __age
>>          else:
>>              raise AttributeError
>>
>>
>>but is there an existing mixin helper class in Python (or one someone 
>>has written) already that will assist with this? (Just not wanting to 
>>reinvent the wheel....)
> 
> 
> Too late.
> 
> py> class Example:
> ...     age = 0
> ...
> py> Example.age
> 0
> py> Example.aeg
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: class Example has no attribute 'aeg'
> 
> It works for instances too:
> 
> py> Example().aeg
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: Example instance has no attribute 'aeg'
> 
> 
> Your __getattr__ code is completely unnecessary.

Sorry, as I noted in another reply not long ago, I was having a 'braino' 
and not saying what I actually meant!
What I was talking about was the accidental _setting_ of the wrong 
attribute.
And the mixin class I'm looking for is one that could be told what were 
valid attributes for the class, and would then catch the situation where 
you mis-spelt an attribute name when setting an attrib.

thanks!
alex






> 
> 
> 



More information about the Python-list mailing list