"Vincent Davis" <vinc...@vincentdavis.net> wrote

class B():
 def __init__(self, b1, b2):
    self.fooa = b1
    self.foob = b2

I assume thats what you really meant!

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,

define a method of the class, say bigprint()

def bigprint(self, limit=5):
    if self.fooa > limit: print self.fooa

about is how I iterate over the values of fooa.

Iterate over the objects and call the method. Make the object do the work, your code should not need to know about the internal attributes of the object.

For x in alist:
     x.bigprint()

Is that the right way or is there a better?
will this work for methods?

Methods are how you should do it. Direct access other than for simple reading of values is a suspicious design smell. Any processing of or rules about the data should be in a method.


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to