[Tutor] OK, dumb question
David Ascher
da@ski.org
Mon, 7 Jun 1999 15:50:32 -0700 (Pacific Daylight Time)
On Mon, 7 Jun 1999, K P wrote:
> I seem to be stuck on the littlest of problems, how do I do this in Python:
> iterate through a 'list' (term used loosely) of twelve class variables,
> check each for changes
> class Meat:
> def __init__(self, colour, type):
> self.colour = colour
> self.type = type
> self.flavor = ' '
>
> class Spam:
> def __init__(self):
> self.beef = Meat('red', 'beef')
> self.chicken = Meat('white', 'fowl')
> def quality(self):
> #In this function I would check the type and colour versus a 'chart'
> (probably a dictionary look-up)
> #e.g. if self.beef.colour = 'red' and self.beef.type = 'beef'
> then self.beef.flavor = 'good'
> #In my 'real' script I would be testing 12-20 class member variables
> against a small set of immutable variables
> #what would be the simplest/fastest/most effective way to code that
> in python?
Use getattr()/setattr(), as in:
class Spam:
ingredient_list = ['beef', 'chicken']
#...
def quality(self):
for ingredient_name in self.ingredient_list:
ingredient = getattr(self, ingredient_name)
colour = getattr(ingredient, 'colour')
type = getattr(ingredient, 'beef')
if colour == 'red' and type == 'beef':
ingredient.flavor = 'good'
# or setattr(ingredient, 'flavor', 'good')
Hope this helps.
--david ascher