python create object from string

前端 未结 2 745
误落风尘
误落风尘 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:13

    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
    

提交回复
热议问题