Creating an Instance of a Class with a variable in Python

后端 未结 8 1270
野性不改
野性不改 2020-12-29 05:23

I\'m trying to create a game for my little sister. It is a Virtual Pet sort of thing and the Pet has toys to play with.

I created a class Toy and want t

8条回答
  •  鱼传尺愫
    2020-12-29 05:46

    Given your edit i assume you have the class name as a string and want to instantiate the class? Just use a dictionary as a dispatcher.

    class Foo(object):
        pass
    
    class Bar(object):
        pass
    
    dispatch_dict = {"Foo": Foo, "Bar": Bar}
    dispatch_dict["Foo"]() # returns an instance of Foo
    

提交回复
热议问题