[Tutor] Populating a list with object to be called by a class

Peter Otten __peter__ at web.de
Thu Sep 20 20:35:14 CEST 2012


Ara Kooser wrote:

> Morning,
> 
>   I dug out some old code from 5 years ago to clean up and get in working
> order. It's a simple agent based model. I have class called Ant which
> contains all the ant-like functions.
> 
> I have a list that tracks the ants but I did this is a very crude way. I
> basically copied and pasted everything in there like this:
> 
> ants =
> [Ant("Red_1","Red","yellow_food"),Ant("Yellow_1","Yellow","red_food"),
> 
> Ant("Red_2","Red","yellow_food"),Ant("Yellow_2","Yellow","red_food"),
> 
> Ant("Red_3","Red","yellow_food"),Ant("Yellow_3","Yellow","red_food"),
> 
> Ant("Red_4","Red","yellow_food"),Ant("Yellow_4","Yellow","red_food"),
>           .......]
> 
> I couldn't figure out how to populate the list from a user input. Say if
> the user wanted 50 Red and 50 Yellow ants. So it's hardcoded at 500 which
> is not an elegant solution.
> 
> I went back to work on this over the past couple of days but still can't
> figure out how to populate the list so I end up with Red_1 then Red_2
> etc...

How boooring. Would you like to be called homo_sapiens_853212547?
 
> What would be a good python way to do this?

import os
import posixpath
import random
import urllib
import textwrap

class Ant:
    def __init__(self, name):
        self.name = name
    def fullname(self):
        return self.name + " " + self.family
    def __repr__(self):
        return self.fullname()

class RedAnt(Ant):
    family = "McAnt"
class YellowAnt(Ant):
    family = "O'Ant"

NAMES_URL = "http://www.gro-scotland.gov.uk/files1/stats/pop-names-07-t4.csv"
NAMES_FILENAME = posixpath.basename(NAMES_URL)

if not os.path.exists(NAMES_FILENAME):
    urllib.urlretrieve(NAMES_URL, NAMES_FILENAME)
    
names = []
with open(NAMES_FILENAME) as f:
    for line in f:
        names += line.split(",")[0::3]
names = filter(bool, names)

ants = [random.choice((RedAnt, YellowAnt))(name)
        for name in random.sample(names, 20)]
print textwrap.fill(str(ants), 50)

Let's do a sample run of the script:

$ python ants.py 
[Sharon McAnt, Shreeram O'Ant, John-Michael McAnt,
Patricia McAnt, Lorne McAnt, Kelso O'Ant, Muryam
O'Ant, Keilee O'Ant, Timothy O'Ant, Anastacia
O'Ant, Zhong O'Ant, Lyndsay O'Ant, Michal McAnt,
Emily McAnt, Juwairiyah McAnt, Sukhveer McAnt,
Philippa McAnt, Mcbride McAnt, Kaidan McAnt, Sasha
O'Ant]

> Thank you for your time.

You're welcome ;)



More information about the Tutor mailing list