1

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
7
  • 4
    Thou shalt not use object as a variable name. Crazy things will happen. Commented Aug 2, 2012 at 12:58
  • 1
    I'm not sure what you're trying to accomplish, but you never define a2. Commented Aug 2, 2012 at 12:59
  • See OPs previous question for context. Commented Aug 2, 2012 at 12:59
  • 1
    Also, you need to rework your design. Use a dictionary or some other kind of association. Commented Aug 2, 2012 at 13:00
  • I have to create multiple instances of Class and there value is output from some other part of script so that's why i have to store them in some variable. But at some point in script, i want to access those instances. So i am running into this problem now. Is there any other solution to solve it? Commented Aug 2, 2012 at 13:02

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

@lazyr, i was confused with its usage in functions. Anyways thanks so much for your help!!
@sarbjit No problem. But you really should look through at least chapters 3, 4 and 5 of the python tutorial, so that you get a basic understanding of the way things work. It's stuffed with practical and nifty things you will need all the time, if you know them.
1

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.

3 Comments

This is just an example to show my problem. In my actual script, variable b2 was used only for creation of multiple instances and therefore can't be used as such. Only its value which is unique can be used to access the instance that it created.
It means it is not possible and i have to think of some other solution?
Use a dictionary as suggested elsewhere. From your question, I just wasn't sure whether you knew how Python works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.