Alan Gauld wrote: > > "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. > >
Personally, I often thought input/output inside an object is a design smell (except for debugging), preferring something like this: class B(object): def __init__(...): ... def big(self, limit=5): return (self.fooa > limit) alist = [...] for y in (x for x in alist if x.big()): print y.fooa although admittably often it could make certain codes more difficult to write; and in some cases the practical approach would be warranted. This is especially true as the codebase gets larger. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor