A __getattr__ for class methods?

Roland Heiber newstonne at web.de
Wed Feb 8 13:28:08 EST 2006


Dylan Moreland wrote:
> I have a metaclass generating basic properties such as .name and .city,
> but I don't want to generate a class method for every permutation of
> the attributes. I'd like to have something much like __getattr__ for
> instance attributes, so that if a method like
> Person.find_by_city_and_email cannot be found, I can construct a call
> to the basic find method that hides the SQL. Is there any way of doing
> this, or am I trying to mirror a functionality that Python simply does
> not have?
> 

I don't get it? __getattr__ is exactly what you are looking for:

http://docs.python.org/ref/attribute-access.html#l2h-206

__getattr__( self, name)

Called when an attribute lookup has not found the attribute in the usual 
places (i.e. it is not an instance attribute nor is it found in the 
class tree for self). name is the attribute name. This method should 
return the (computed) attribute value or raise an AttributeError exception.

HtH, Roland



More information about the Python-list mailing list