Prev: MySQL One More Again
Next: Python 3 and setuptools
From: Ray on 16 Jul 2010 12:01 class Test: def __init__(self): self.value=0 def change(self, val): self.value=val if __name__=='__main__': for x in range(10): x=Test() """ the question is how do i call x.value outside of that for loop? something like print x.value ? """ thanks for any help.
From: MRAB on 16 Jul 2010 12:17 Ray wrote: > class Test: > def __init__(self): > self.value=0 > def change(self, val): > self.value=val > > if __name__=='__main__': > for x in range(10): > x=Test() > """ > the question is how do i call x.value outside of that for loop? > something like > print x.value ? > """ > > thanks for any help. Have you tried it? Why are you using the same name for the loop variable and the instance you're creating?
From: Ray on 16 Jul 2010 12:22 On Jul 16, 12:17 pm, MRAB <pyt...(a)mrabarnett.plus.com> wrote: > Ray wrote: > > class Test: > > def __init__(self): > > self.value=0 > > def change(self, val): > > self.value=val > > > if __name__=='__main__': > > for x in range(10): > > x=Test() > > """ > > the question is how do i call x.value outside of that for loop? > > something like > > print x.value ? > > """ > > > thanks for any help. > > Have you tried it? > > Why are you using the same name for the loop variable and the instance > you're creating? yes. I need to create instance. the code above is just a example. on real code, it read a dict, and create the instance from dict.keys() name. that dict is build dynamic from database.
From: Andre Alexander Bell on 16 Jul 2010 12:37 On 07/16/2010 06:01 PM, Ray wrote: > if __name__=='__main__': > for x in range(10): > x=Test() > """ > the question is how do i call x.value outside of that for loop? > something like > print x.value ? > """ You would have to keep references to your Test objects (untested code): if __name__ == '__main__': test_objects = [] for x in range(10): test_objects[x] = Test() print test_objects[0].value ... You may want to rewrite this as a list comprehension if __name__ == '__main__': test_objects = [Test() for i in range(10)] print test_objects[0].value Andre
From: Ray on 18 Jul 2010 07:36 thanks a lot. I was really stupid. of course I should keep a references to use it later.
|
Pages: 1 Prev: MySQL One More Again Next: Python 3 and setuptools |