python create object from string

前端 未结 2 744
误落风尘
误落风尘 2021-01-15 19:35

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):
         


        
2条回答
  •  不要未来只要你来
    2021-01-15 20:37

    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]()
    

提交回复
热议问题