[Tutor] list of instance objects, access attribute
Kent Johnson
kent37 at tds.net
Fri Jun 19 02:09:22 CEST 2009
On Thu, Jun 18, 2009 at 7:32 PM, Vincent Davis<vincent at vincentdavis.net> 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?
What you have is fine.
> will this work for methods?
Sure. Try it!
Kent
More information about the Tutor
mailing list