[Tutor] For Loop Question

Alan Gauld alan.gauld at btinternet.com
Mon Dec 24 03:02:36 CET 2012


On 24/12/12 01:16, Mitya Sirenef wrote:
> On 12/23/2012 08:03 PM, Tom Tucker wrote:
>>
>>
>> Python Gurus,
>> I got a question for ya.  Below I have three instance variables
>> (self.A, self.B, etc).  How can I use the below
>> for loop for A, B, C to also call those instance variables?
>>

Your example is not entirely clear.

You do realize that self is only defined inside a method? Therefore,
by implication, all of your code should lie inside a class and most
of it inside a single method? Therefore, I'd expect your code
to look like:


>> <some code>
>> .....
>> .....
class MyClass:
   def someMethod(self):
>>  self.A   = 1
>>  self.B   = 2
>>  self.C   = 3
>>
   def someOtherMethod(self):
>> myDict = {'A': 1, 'B': 2, 'C': 1}
>> for x in [A, B, C]:

in which case this becomes, as Mitya suggests:

    for key in myDict:
       if myDict[key] == getattr(self, key):

 >       print "Yep, we have a match!"
 >     else:
 >       print "Sorry..No match!"

But, whatever you are trying to do here, there is very likely a better 
way to do it. We just don't know enough context to offer alternatives.


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



More information about the Tutor mailing list