[Tutor] Looping over lists of objects

Etrade Griffiths etrade.griffiths at dsl.pipex.com
Mon Apr 24 18:42:02 CEST 2006


Ed

the problem is that my original code did not have the closing brackets for 
the method calls get_a and get_b whereas the code snippet I posted 
did.  That's probably why your version works and mine failed.  Thanks for 
your help!

Alun

At 17:19 24/04/2006, Ed Singleton wrote:
>On 24/04/06, Etrade Griffiths <etrade.griffiths at dsl.pipex.com> wrote:
> >  Hi
> >
> >  just feeling my way into Python with a  small app that reads data from
> > file, creates objects using that data, stores the objects in a list, loops
> > over the list doing comparison tests to filter out various 
> objects.  Here is
> > a code snippet:
> >
>[snip]
> >
> >  Trying to debug this using IDLE.  The calls x.get_a and x.get_b always
> > return zero so something is going wrong somewhere.  I think I'm either not
> > storing the objects correctly or retrieving them correctly but no idea why!
> > All suggestions gratefully received!!!
>
>I added some test input to give the code below, and it works fine for
>me.  Can you give us some test input that fails for you?  Can you also
>show us your test() function as it may the code in there that is
>failing.
>
>Ed
>
>class myObj:
>     def __init__(self,a,b):
>         self.a=a
>         self.b=b
>
>     def get_a(self):
>         return self.a
>
>     def get_b(self):
>         return self.b
>
>
>input = ["1 2 3", "4 5 6"]
>
>L1=[]
>nobj=0
>
>for line in input:
>         L0=line.split()
>         a=L0[1]
>         b=L0[2]
>         nobj=nobj+1
>
>         an_obj=myObj(a,b)
>
>         L1.append(an_obj)
>
># Filter data
>
>for i in range(1,nobj):
>         for x in L1:            # ... loop over all objects in list
>                 print "a -> ", x.get_a()             # ... get value
>of a from current object
>                 print "b -> ", x.get_b()
>
>
>It returns:
>
>a ->  2
>b ->  3
>a ->  5
>b ->  6




More information about the Tutor mailing list