setattr getattr confusion

Carl Banks pavlovevidence at gmail.com
Sat Dec 8 08:03:17 EST 2007


On Dec 8, 6:06 am, Donn Ingle <donn.in... at gmail.com> wrote:
> Hi,
>  Here's some code, it's broken:
>
> class Key( object ):
>     def __init__(self):
>         self.props = KeyProps()
>     def __getattr__(self, v):
>         return getattr( self.props,v )
>     def __setattr__(self,var,val):
>         object.__setattr__(self.props,var,val)

If you define __setattr__ you can't initialize attributes the ordinary
way.  Instead, use self.__dict__.  (Once it's initialized, you can
refer to it in the ordinary way.)  So do it like this:

class Key(object):
    def __init__self):
        self.__dict__['props'] = KeyProps()
    def __getattr__(self,var):
        return getattr(self.props,var)
    def __setattr__(self,var,val):
        setattr(self.props,var,val)


Carl Banks



More information about the Python-list mailing list