general class functions

syd syd.diamond at gmail.com
Mon Nov 1 20:09:53 EST 2004


In my project, I've got dozens of similar classes with hundreds of
description variables in each.  In my illustrative example below, I
have a Library class that contains a list of Nation classes.  In one
case, I might want a Library class with only Nations of with the
continent variable "Europe", and so I'll do something like
library.getContinent('Europe') which will return a Library() instance
with only European nations.  Similarly, I could also want a Library()
instance with only 'small' size nations.

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.

This stumped everyone I work with.  Help would be greatly
appreciated!!

#!/usr/bin/python
class Library:
  def __init__(self,list=None):
    self.list=list
  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 getContinent(self,continent):
    library=Library()
    for nation in self.list:
      if nation.isContinent(continent)==True:
        library.add(nation)
    return library
  def getSize(self,size):
    library=Library()
    for nation in self.list:
      if nation.isSize(size)==True:
        library.add(nation)
    return library
  def getNameList(self):
    outList=[]
    for nation in self.list:
      outList.append(nation.name)
    return outList
  class Nation:
    def __init__(self,name=None,continent=None,size=None):
      self.name=name # eg, Spain
      self.continent=continent # eg, Europe
      self.size=size # eg, medium
    def isContinent(self,continent):
      if self.continent==continent: return True
      else: return False    def isSize(self,size):
      if self.size==size: return True
      else: return False

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.getContinent('Europe').getNameList()
print library.getContinent('Europe').getSize('small').getNameList()



More information about the Python-list mailing list