Dynamically Generate Methods
Ian Kelly
ian.g.kelly at gmail.com
Fri Nov 18 13:04:19 EST 2011
On Fri, Nov 18, 2011 at 7:51 AM, GZ <zyzhu2000 at gmail.com> wrote:
> Hi,
>
> I have a class Record and a list key_attrs that specifies the names of
> all attributes that correspond to a primary key.
>
> I can write a function like this to get the primary key:
>
> def get_key(instance_of_record):
> return tuple(instance_of_record.__dict__[k] for k in key_attrs)
>
> However, since key_attrs are determined at the beginning of the
> program while get_key() will be called over and over again, I am
> wondering if there is a way to dynamically generate a get_ley method
> with the key attributes expanded to avoid the list comprehension/
> generator.
(Accidentally sent this to the OP only)
This is exactly what the attrgetter factory function produces.
from operator import attrgetter
get_key = attrgetter(*key_attrs)
But if your attribute names are variable and arbitrary, I strongly
recommend you store them in a dict instead. Setting them as instance
attributes risks that they might conflict with the regular attributes
and methods on your objects.
Cheers,
Ian
More information about the Python-list
mailing list