A __getattr__ for class methods?
Michael Spencer
mahs at telcopartners.com
Wed Feb 8 13:25:37 EST 2006
Dylan Moreland wrote:
> I'm trying to implement a bunch of class methods in an ORM object in
> order to provide functionality similar to Rails' ActiveRecord. This
> means that if I have an SQL table mapped to the class "Person" with
> columns name, city, and email, I can have class methods such as:
>
> Person.find_by_name
> Person.find_by_city_and_name
> Person.find_by_name_and_city_and_email
>
> 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, ...
Sure, define __getattr__ on the type of the class i.e., the metaclass, just as
you define it on a class to provide default-attribute-lookup to its instances:
>>> class A(object):
... class __metaclass__(type):
... def __getattr__(cls, attr):
... return "%s.%s" % (cls.__name__, attr)
...
>>> A.somefunc
'A.somefunc'
>>> A.someotherfunc
'A.someotherfunc'
>>>
HTH
Michael
More information about the Python-list
mailing list