[Tutor] creating objects in a loop
Alexandre Ratti
alex@gabuzomeu.net
Wed, 03 Apr 2002 00:10:35 +0200
Hello Brad,
At 15:14 02/04/2002 -0500, you wrote:
>From: "Brad Reisfeld" <brad.reisfeld@colostate.edu>
>Date: Tue, 2 Apr 2002 11:33:37 -0700
>Subject: [Tutor] creating objects in a loop
>I was wondering if there is an efficient way to create objects based on
>looping through members of a list or dictionary.
>
>For instance, suppose I have
>
> >>> class Pets:
>... def __init__(self, name):
>... self.name = name
>
> >>> petlist = [('cat','fluffy'),('dog','fido'),('gorilla','spike')]
This is a bit off-topic, but you might be interested in using functions as
class factories:
class Pets:
def __init__(self, name):
self.name = name
def factory(theClass, *args):
"theClass is a class object."
return theClass(*args)
def factoryFromName(className, *args):
"className is a string."
return eval(className)(*args)
def petFactory(arg):
# This could be extended to accept a list of args
# and return a list of class instances
return Pets(arg)
if __name__ == "__main__":
cat = factory(Pets, "fluffy")
print cat
monkey = factoryFromName("Pets", "foo")
print monkey
pet = petFactory("bombix")
print pet
<__main__.Pets instance at 00FBFA7C>
<__main__.Pets instance at 00FBEFDC>
<__main__.Pets instance at 00FBB90C>
Also, if you have a lot of pets to handle, you could use a collection class
to manage them. Eg.:
class BunchOfPets:
def __init__(self):
self.petDict = {}
def addPet(self, name):
pet = Pets(name)
self.petDict[name] = pet
def getPet(self, name):
if self.petDict.has_key(name):
return self.petDict[name]
else:
return None
def getPetCount(self):
return len(self.petDict)
if __name__ == "__main__":
bunch = BunchOfPets()
bunch.addPet("snafu")
print bunch.getPetCount()
print bunch.getPet("snafu")
1
<__main__.Pets instance at 018592FC>
Cheers.
Alexandre