[Tutor] list of instance objects, access attribute
Dave Angel
davea at ieee.org
Fri Jun 19 03:16:21 CEST 2009
Vincent Davis wrote:
> given a class like
> class B():
> def __init__(self, b1, b2):
> ??? self.fooa = fooa
> ??? self.foob = foob
>
> Ok now I have several instances in a list
> b1 = B(1, 2)
> b2 = B(3, 4)
> b3 = B(9, 10)
> alist = [b1, b2, b3]
>
> Lets say for each instance of the class I want to print the value of
> fooa if it is greater than 5. How do I do this, what I am unclear
> about is how I iterate over the values of fooa. As I write this I am
> thinking of trying
> For x in alist:
> if x.fooa > 5 : print(x.fooa)
>
> Is that the right way or is there a better?
> will this work for methods?
>
> Thanks
> Vincent Davis
>
Did you actually try to run this code? There are at least three syntax
problems.
1) you need to indent the body of the class
2) you need to match the formal parameters of __init__() with their usage.
3) you need to change 'For' to 'for'
class B():
def __init__(self, b1, b2):
self.fooa = b1
self.foob = b2
#Ok now I have several instances in a list
b1 = B(1, 2)
b2 = B(3, 4)
b3 = B(9, 10)
alist = [b1, b2, b3]
for x in alist:
if x.fooa > 5 : print(x.fooa)
And then the answer is yes, that's a reasonable way to iterate over the
objects, displaying the ones with an attribute of specified value.
However, as a style issue, I'd split the print on its own line. Another
change I'd make is to explicitly specify object as the base class for
class B.
More information about the Tutor
mailing list