general class functions
syd
syd.diamond at gmail.com
Wed Nov 3 11:00:15 EST 2004
> Instead of
> return self.__dict__[name]
> you need
> raise AttributeError, name
Booyah, Kent! This works. For posterity, I'll dump a working code:
#!/usr/bin/python
class Library(object):
def __init__(self,list=None):
self.list=list
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:
raise AttributeError,name
def add(self,nation):
try: self.list.append(nation)
except: self.list=[nation]
def defineNation(self,name,continent,size):
nation=Library.Nation()
nation.name=name
nation.continent=continent
nation.size=size
self.add(nation)
def getNameList(self):
outList=[]
for nation in self.list:
outList.append(nation.name)
return outList
class Nation(object):
def __init__(self,name=None,continent=None,size=None):
self.name=name # eg, Spain
self.continent=continent # eg, Europe
self.size=size # eg, medium
library=Library()
library.defineNation('Spain','Europe','medium')
library.defineNation('USA','NorthAmerica','large')
library.defineNation('Luxembourg','Europe','small')
library.defineNation('Portugal','Europe','medium')
print library.getNameList()
print library.get_continent('Europe').getNameList()
More information about the Python-list
mailing list