python create object from string

前端 未结 2 723
误落风尘
误落风尘 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条回答
  • 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
    
    0 讨论(0)
  • 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]()
    
    0 讨论(0)
提交回复
热议问题