1

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 !

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm brand new to Python, under what circumstances would you take this approach?
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 .
In 2.x this only works when explicitly inheriting from object. class X(object): ...
@Kev: As the question as top-level question in SO, it's hard to tackle a question like that in comments.
2
getattr(x,"value=",99)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.