-1

In Python, I would like to instantiate objects of a class where the objects are instantiated at run time without using dictionaries? So I can refer to the objects properties from the string entered.

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
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
user1530405
  • 447
  • 1
  • 8
  • 16

1 Answers1

0

Store your user input in a dictionary:

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
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • But I want to use objects rather than dictionaries ! But thanks anyway. – user1530405 Jan 07 '16 at 07:17
  • @user1530405: I think you are confusing a name, which is an untyped reference, with the object. Using dictionaries in this way is very common in Python - python itself uses such mechanisms all over the place. – cdarke Jan 07 '16 at 07:48