general class functions
Andrea Griffini
agriff at tin.it
Tue Nov 2 01:44:20 EST 2004
On 1 Nov 2004 17:09:53 -0800, syd.diamond at gmail.com (syd) wrote:
>My question follows: is there a way I can make a general function for
>getting a subclass with my specific criteria? For instance, can I
>pass in an equivalence test or something like that? I have hundreds
>of variables like "nation", "continent", and so forth, and do want to
>write a separate "get______" function for each.
Adding the following method to Library
def __getattr__(self,name):
if name.startswith("get_"):
attrname = name[4:]
def filter(value):
library=Library()
for nation in self.list:
if getattr(nation,attrname) == value:
library.add(nation)
return library
return filter
else:
return self.__dict__[name]
you will be able to write
L.get_continent('Europe').get_size('small')
because for anything starting with "get_..." will be
generated on the fly a filtering function that looks
for exact match of an attribute. No need for
getContinent, getSize, isContinent and isSize.
HTH
Andrea
More information about the Python-list
mailing list