如何在运行时使用不同的名称实例化现有类的对象?

时间:2016-01-07 06:39:46

标签: python class object

在Python中,我想实例化一个类的对象,其中对象在运行时实例化而不使用字典?所以我可以从输入的字符串中引用对象属性。

class Mammal(object)
    pass

Dog = raw_input("Mammal: ")  - Typed in "Dog"
Dog = Mammal
Dog.Breed = "Terrier"
Dog.Color = "Brown"

Shark = raw_input("Mammal: ")  - Typed in "Shark"
Shark = Mammal
Shark.Fins = 1

print Dog.Color
print Shark.Fins

1 个答案:

答案 0 :(得分:0)

将您的用户输入存储在字典中:

class Mammal(object)
    pass

mammals = {}
kind = raw_input("Mammal: ")  # Typed in "Dog"
mammals[kind] = Mammal()
mammals[kind].Breed = "Terrier"
mammals[kind].Color = "Brown"

kind = raw_input("Mammal: ")  # Typed in "Shark"
mammals[kind] = Mammal()
mammals[kind].Fins = 1

print mammals['Dog'].Color
print mammals['Shark'].Fins