Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #15904
| Date | 2011-11-18 17:56 +0100 |
|---|---|
| From | Jean-Michel Pichavant <jeanmichel@sequans.com> |
| Subject | Re: Dynamically Generate Methods |
| References | <ad844f2a-8521-4ce4-8dfc-fb7e0fc505ad@q39g2000prg.googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2836.1321635635.27778.python-list@python.org> (permalink) |
GZ 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.
>
> For example, if key_attrs=['A','B'], I want the generated function to
> be equivalent to the following:
>
> def get_key(instance_of_record):
> return (instance_of_record['A'],instance_of_record['B'] )
>
> I realize I can use eval or exec to do this. But is there any other
> way to do this?
>
> Thanks,
> gz
>
>
>
>
Hi,
you may want to do something like
class Record(object):
PRIMARY_KEY = []
def __init__(self):
for key in self.PRIMARY_KEY:
setattr(self, key, None)
def getPrimaryKeyValues(self):
return [ getattr(self, key) for key in self.PRIMARY_KEY]
class FruitRecord(Record):
PRIMARY_KEY = ['fruit_id', 'fruit_name']
JM
PS : there's a high chance that a python module already exists to access
your database with python objects.
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Dynamically Generate Methods GZ <zyzhu2000@gmail.com> - 2011-11-18 06:51 -0800
Re: Dynamically Generate Methods Jean-Michel Pichavant <jeanmichel@sequans.com> - 2011-11-18 17:56 +0100
Re: Dynamically Generate Methods Duncan Booth <duncan.booth@invalid.invalid> - 2011-11-18 17:52 +0000
Re: Dynamically Generate Methods Ian Kelly <ian.g.kelly@gmail.com> - 2011-11-18 11:04 -0700
Re: Dynamically Generate Methods GZ <zyzhu2000@gmail.com> - 2011-11-20 03:23 -0800
csiph-web