Is there a way in Python, that i can use the variable value for creation of Class instance
class Test(object):
def __init__(self, object):
self.name = object
print "Created Object :",self.name
a1 = Test('a1')
print a1.name
b2 = 'a2'
b2 = Test(b2)
print a2.name
In this example, i want the class instance name should be ‘a1’ and ‘a2’ respectively. I cannot directly use the value ‘a2’ as it is computed from some other process, but the class instance name must match it such that it can be accessed.
In the above example, it gives error :
Created Object : a1
a1
Created Object : a2
Traceback (most recent call last):
File "D:\a\h", line 12, in <module>
print a2.name
NameError: name 'a2' is not defined
The closest thing to what you are looking for is to store all your instances in a dictionary:
There is no connection between the name of a variable that references an object and the object itself.