__getattr__ and functions that don't exist

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Fri May 26 16:09:25 EDT 2006


Erik Johnson a écrit :
(snip)
>     I was thinking it would be clean to maintain an interface where you
> could call things like f.set_Spam('ham') and implement that as self.Spam =
> 'ham' 

If all you want to do is to assign 'ham' to self.spam, just do it - no 
need for a setter. And if you worry about possible future needs for 
controlling assignement to spam, internally use another name for it or 
any other computation at this level, then it will be time to refactor 
obj.spam as a property:

class Parrot(object):
   def _set_spam(self, value):
     self._another_attrib = any_computation_here(value)
   def _get_spam(self):
     return some_more_processing_here(self._another_attrib)
   spam = property(_get_spam, _set_spam)

p = Parrot()
p.spam = "ham"
print p.spam

> without actually having to define all the set_XXX methods for all the
> different things I would want to set on my object (as opposed to just making
> an attribute assignment), but I am starting to think that is probably an
> idea I should just simply abandon.

indeed.



More information about the Python-list mailing list