sarbjit
sarbjit

Reputation: 3894

Using variable value for creating class instance

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

Upvotes: 1

Views: 224

Answers (3)

mgilson
mgilson

Reputation: 309861

Any time you want to dynamically create variable names, you need to stop and tell yourself that a dictionary is a better way to go. If you want the class instance to be available anywhere (which is also not the best idea), but here's how you can do that:

class Test(object):
    instance_dict={}
    def __init__(self,name):
        self.name=name
        self.instance_dict[name] = self

Now you can use this class:

a1 = Test("a1")
print a1 is Test.instance_dict["a1"] #True
b1 = Test("a2")
print b1 is Test.instance_dict["a2"] #True

In other words, the instance_dict class attribute keeps a handle on the most recently created instance with a particular name so you have a handle on the instances anywhere that Test is available.

However, I do not recommend this type of design. The downsides here are the same as the downsides with using global variables. It will probably become difficult to maintain, hard to tell what exactly is going on, etc. simply because the flow of data through your program is not well ordered.

Upvotes: 4

chepner
chepner

Reputation: 530970

The closest thing to what you are looking for is to store all your instances in a dictionary:

class Test(object):
    def __init__(self, n):
        self.name = n
        print "Created Object :",self.name

d = {}
d['a1'] = Test('a1')
print d['a1'].name
b2 = 'a2'
d[b2] = Test(b2)
print d['a2'].name

There is no connection between the name of a variable that references an object and the object itself.

Upvotes: 3

Aaron Digulla
Aaron Digulla

Reputation: 328556

Try print b2.name instead.

Note: The name name doesn't mean anything special to Python. "Giving your class a name" means nothing to Python, it just executes the code that you write. "Giving your class a name" means something to you but Python can't and won't read your mind :-)

So setting the name of the instance referenced by b2 to a2 doesn't magically create a reference a2.

This introduction to variable names might help: Learn to Program Using Python: Variables and Identifiers

In a nutshell, if you write

a = 'x'

Python

  1. Creates a string instance
  2. Assigns a value to that string instance (the text x)
  3. Assigns a reference to this new string instance to the alias a

If you then write:

b = a

there is still only a single string instance in memory. You only created a second alias b which references the same string instance as a.

Upvotes: 1

Related Questions