[Tutor] For Loop Question

Dave Angel d at davea.name
Mon Dec 24 05:17:49 CET 2012


On 12/23/2012 09:02 PM, Alan Gauld wrote:
> 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]:
>
But A, B, and C have no values yet.  Perhaps the OP means
            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


-- 

DaveA



More information about the Tutor mailing list