[Tutor] __getattr__(): Is this right?

Eric Brunson brunson at brunson.com
Tue Oct 16 03:54:56 CEST 2007


Allen Fowler wrote:
> I seem to be having an issue with __getattr__() being called even if 
> the proporite already exists... I thought that this was not supposed 
> to happen.

I think you've misunderstood.  __getattr__() should always be called, it
allows you to intercept and reimplement the behavior of a attribute
lookup to suit your needs.  Typically, my __getattrs__() look like this:

def __getattr__( self, attr ):
     if has_attr( usuallysomethingotherthanself, attr ):
         do_one_thing()
     else:
         do_something_else()

>
> Is there a typo somewhere, or I do i misunderstand things?
>
> class someclass(object):
>
>     
>     def __init__(self, **kargs):
>       
>         self.valid_props =  [ 'foo', 'bar', 'baz' ]
>         
>         for prop in self.valid_props:
>             if kargs.has_key(prop):
>                 self.__setattr__(prop, kargs[prop])
>     
>     def __getattr__(self,attr):
>         if attr in self.valid_props:
>             # This print should throw an exception,
>             # but it does not. It shows the value.
>             print "Oh no.. This was not found: %s" % self.__dict__[attr]
>             return 'n/a'
>         else:
>             raise AttributeError, attr
>
>
> ------------------------------------------------------------------------
> Boardwalk for $500? In 2007? Ha!
> Play Monopoly Here and Now 
> <http://us.rd.yahoo.com/evt=48223/*http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow> 
> (it's updated for today's economy) at Yahoo! Games.
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   




More information about the Tutor mailing list