python create object from string

社会主义新天地 提交于 2020-05-23 11:16:11

问题


I have the next situation. The goal of the following method is to return the object created from the incoming string. So I have:

class Situation(Generator):
    pass

And the method inside parent class:

class Generator(object):
    def createsituation(self, stringsituation="situation"):
        return "Instance of Situation"

The incoming string always equals to string "situation". Is it possible in python?


回答1:


You can easily map strings to classes, yes. Classes are just more objects, you can store them in other Python objects.

You can manually build a dictionary mapping strings to classes:

classes = {'situation': Situation}

You can automate this a little by creating a class decorator, perhaps:

classes = {}
def register(cls):
    classes[cls.__name__.lower()] = cls
    return cls

@register
class Situation(Generator):
    # ...

Each class you prefix with @register will be added to the dictionary, with the class name lowercased as the key.

or you can use the globals() function to get a dictionary of all globals in your module. The latter is a little... overkill and also a security hazard, you could end up giving end-users way more access than you bargained for, as that also gives them other classes and functions you didn't mean to expose.

Once you have a dictionary, just access the right class and call it:

class Generator(object):
    def createsituation(self, stringsituation="situation"):
        return classes[stringsituation]()



回答2:


If I understood you correctly, you want to create the Situation object from Generator's createsituation method. So you need the appropriate constructor in Situation class with passed string as an argument. Little changes in your code will achieve this:

class Situation(object):
    def __init__(self, string):
        print string

class Generator(object):
    def createsituation(self, stringsituation="situation"):
        return Situation(stringsituation)

g = Generator()
sitObj = g.createsituation("new_situation") # prints "new_situation" from Situation constructor


来源:https://stackoverflow.com/questions/30654328/python-create-object-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!