create dynamic instance

R

Ray

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.
 
M

MRAB

Ray said:
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?
 
R

Ray

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.
 
A

Andre Alexander Bell

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
 
R

Ray

thanks a lot. I was really stupid.
of course I should keep a references to use it later.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,111
Latest member
KetoBurn
Top