setattr getattr confusion

James Stroud jstroud at mbi.ucla.edu
Sat Dec 8 06:39:45 EST 2007


Donn Ingle 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)
>         
> class KeyProps(object):
>     def __init__(self):
>         self.x="NOT SET YET"
> k1=Key()
> 
> It does not run because of the recursion that happens, but I don't know how
> to lay this out.
> 
> I am trying to set the x value within props within Key:
> k1.x="DAMN"
> print k1.x
> 
> It seems to work, but it's really making a new 'x' in k1.
> print k1.props.x
> Shows "NOT SET YET", thus proving it failed to set x here.
> 
> I want to change k1.props.x by k1.x="something new" -- can this be done?
> 
> \d
> 

You will want to study the attribute proxy recipe:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/510402

Also, its not obvious how what you seem to be describing is different from:

class Key(object):
   def __init__(self):
     self.x = 'NOT SET YET'
     self.props = self

e.g.

py> class Key(object):
...   def __init__(self):
...     self.x = 'NOT SET YET'
...     self.props = self
...
py> k = Key()
py> k.props.x
'NOT SET YET'
py> k.x
'NOT SET YET'
py> k.x = "DAMN"
py> k.x
'DAMN'
py> k.props.x
'DAMN'

So you might want to describe your use-case.



James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com



More information about the Python-list mailing list