0

As in title. I want to know if is it possible to change string into class and link it with it. Example of what I have in mind:

class Example:
    def __init__(self, name, variable):
        self.n = name
        self.v = variable

tempclass = Example("tempclass", 1)
class1 = Example("class1", 2)
inpt = raw_input()
inpt()
stringtoclass = None

def function1():
    stringtoclass = "%s" % (inpt)
    ## function that change string into link to specific class and gives 
    print stringtoclass.v
8
  • tempclass does not represent a class: it is a variable/binding. Example is a class. So what is really desired? Commented Sep 7, 2015 at 5:23
  • 1
    do you want to get the instance of class or the class itself? Can you explain what you want a bit more? Commented Sep 7, 2015 at 5:28
  • Where did you get the string from? Commented Sep 7, 2015 at 5:42
  • 1
    @Gunnm You should ask us how to help with what you actually wanna do, not how to write the solution you think you need. What are you using this code for? Edit: In this case. Since you're clearly not sure what you should do Commented Sep 7, 2015 at 5:49
  • 1
    You probably need serialization with marshal or pickle Commented Sep 7, 2015 at 6:14

2 Answers 2

2

I believe you can use dictionary for this. Dictionary are key:value based data structures. You can use the string as the key and the class object as the value. Example -

class Example:
    def __init__(self, name, variable):
        self.n = name
        self.v = variable

obj_dict = {}
obj_dict['tempclass'] = Example("tempclass", 1)
obj_dict['class1'] = Example("class1", 2)

def function1(obj_dict, stringforobj):
    obj = obj_dict.get(stringforobj)
    if obj is not None:
        print obj.v
    else:
        print "Notfound"

inpt = raw_input()
function1(obj_dict, inpt)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this is the answer I was looking for.
1

Anand S Kumar's answer is better, but if you anyway want to get global variable by it's name, you can use globals() function.

In your example it would be:

class Example:
        def __init__(self, name, variable):
        self.n = name
        self.v = variable

tempclass = Example("tempclass", 1)
class1 = Example("class1", 2)

inpt = raw_input()

stringtoclass = globals()[inpt]
print stringtoclass.v

Comments

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.