views:

1066

answers:

2

I was trying to write some code that would check if an item has some attributes , and to call them . I tried to do that with getattr , but the modifications wouldn't be permanent . I made a "dummy" class to check upon this . Here is the code I used for the class :


class X:                                         
   def __init__(self):
     self.value = 90  
   def __get(self):   
     return self.value
   def __set(self,value):
     self.value = value  
   value = property(__get,__set)

x = X()
print x.value # this would output 90
getattr(x,"value=",99) # when called from an interactive python interpreter this would output 99
print x.value # this is still 90 ( how could I make this be 99 ? ) 

Thanks !

+8  A: 

You need to do something like

class X:                                         
   def __init__(self):
     self._value = 90  

   def _get(self):   
     return self._value

   def _set(self, value):
     self._value = value  

   value = property(_get, _set)

Note that the "internal" variable has to have a different name than the property (I used _value).

Then,

setattr(x, 'value', 99)

should work.

dF
That's what I was looking for! Thank you !
Geo
I'm brand new to Python, under what circumstances would you take this approach?
Kev
I'm writing a class that adds some XPath support to BeautifulSoup , and I need to check if soup has an attribute passed as a string .
Geo
In 2.x this only works when explicitly inheriting from object.class X(object): ...
Algorias
@Kev: As the question as top-level question in SO, it's hard to tackle a question like that in comments.
S.Lott
+1  A: 
getattr(x,"value=",99)

returns 99 because x has no attribute "value=" (note the equals sign), so getattr returns the supplied default (99).

Aaron Digulla
it seems the OP confused getattr and setattr...
Algorias