noob help request - how to make a list of defined class?

Jon Clements joncle at
Tue Sep 9 22:53:57 CEST 2008

On Sep 9, 3:11 pm, nuffno... at wrote:
> I have defined two classes with one common field (called code) and
> several different fields.
> In class A there is only one instance of any given code as all items
> are individual.
> In class B, there may be none, one or many instances of each code, as
> there can be any number of Bs referring to a single A.
> I need to make a list of Bs, remove dupes, and then create a list of
> As that have Bs.
> (I hope this makes sense!)
> with much research and reading of my book I managed to get this
> working,  but at one stage I had errors that talked about being unable
> to concatenate type A.  So I converted my As to string, and then did a
> split on commas to make a list.  This worked fine for all the As that
> didn't have a comma in a field (about 85%) but I can't help feeling
> that this is a kludge, and that if Icould find a way to get a proper
> list of As instead of a list of lists created by converting to string
> and splitting, then my app would work properly.
> So I am hoping some of the nice folk here will help me out.
> The relevent function looks like this:
> def gen_B_A_list():
>     Bcodes = get_codes()
>     all_As = read_A("A.csv")
>     B_A = []
>     for i in range(len(codes)):
>         Bcode = Bcodes[i]
>         for A in all_As:
>             filename = getattr(A, 'code')
>             if filename == Bcode:
>                 BA = str(A)
>                 BA = string.split(BA, ',')
>                 B_A.append(BA)
>     return B_A
> The element in question is after if filename == Bcode.   How do I
> construct a list of my defined class A objects here instead of this?
> ( I can post the full code if needed,  just thought it was better
> netiquette not to)
> nuffi

Looks like homework, but as you've made some kind of effort, some
hints to where to refer to in the manual.

1) Use the csv module for reading CSV files
2) A dict maps one value to another... (check it out)
3) Don't use getattr, use member access (the . symbol, eg: A.code)
4) The for statement can loop over each item in term without an
explicit range (eg, for bcode in codes...)
5) Read the help for str, and  read up on how to create objects, for
instance str(A) returns A's string representation, while A() creates a
new A object...

Work your way through a python tutorial and make sure you understand
the examples and principals... It might take you a while though, so I
hope the assignment's not due soon!


More information about the Python-list mailing list