是否可以使用某些函数或命令将字符串更改为类?

时间:2015-09-07 05:20:09

标签: python string class python-2.7 python-3.x

如标题所示。我想知道是否可以将字符串更改为类并将其与之链接。我想到的例子:

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

2 个答案:

答案 0 :(得分:2)

我相信您可以使用dictionary。字典是基于key:value的数据结构。您可以使用字符串作为键,使用类对象作为值。示例 -

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)

答案 1 :(得分:1)

Anand S Kumar的答案更好,但如果你想通过它的名字获得全局变量,你可以使用globals() function

在你的例子中,它将是:

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