Search code examples
pythonlistclassdictionaryinstance

How to include a list of instances from a class in a dictionary?


I created a custom class with the following properties, methods and instances:

class wizard:
  def __init__(self, first, last, pet, petname, patronus):
    self.first = first
    self.last = last
    self.pet = pet
    self.petname = petname
    self.patronus = patronus

  # Methods
  def fullname(self):
    return '{} {}'.format(wizard1.first, wizard1.last)

  def tell_pet(self):
    return '{} {}{} {} {} {}'.format(wizard1.first, wizard1.last,'\'s', wizard1.pet, 'is called', wizard1.petname)

  def expecto_patronum(self):
    return '{} {} {}'.format('A', wizard1.patronus, "appears!")


# Instances
harry = wizard('Harry', 'Potter', 'Owl', 'Hedwig', 'Stag')
ron = wizard('Ron', 'Weasley', 'Owl', 'Pigwidgeon', 'Dog')
hermione = wizard('Hermione', 'Granger', 'Cat', 'Crookshanks', 'Otter')
malfoy = wizard('Draco', 'Malfoy', 'Owl', 'Niffler', 'Dragon')

Now I want to create a dictionary which stores instances of the class wizard.

hogwarts = {harry, ron, hermione, malfoy}

However, all I get as an output is the following:

{<__main__.wizard object at 0x7fa2564d6898>, 
<__main__.wizard object at 0x7fa2564d61d0>, 
<__main__.wizard object at 0x7fa2564d6dd8>, 
<__main__.wizard object at 0x7fa2564bf7f0>}

Instead I'd like the dictionary to print out the information which is stored in the instances. How can I do that?


Solution

  • You need to use self to use your class attributes.

    class wizard:
      def __init__(self, first, last, pet, petname, patronus):
        self.first = first
        self.last = last
        self.pet = pet
        self.petname = petname
        self.patronus = patronus
    
      # Methods
      def fullname(self):
        return '{} {}'.format(self.first, self.last)
    
      def tell_pet(self):
        return '{} {}{} {} {} {}'.format(self.first, self.last,'\'s', self.pet, 'is called', self.petname)
    
      def expecto_patronum(self):
        return '{} {} {}'.format('A', self.patronus, "appears!")
    

    Your dictionary is actually a set. You can just put your instances in a list and iterate through it to print the values as you see fit, like so:

    hogwarts = [harry, ron, hermione, malfoy]
    for student in hogwarts:
        print('{}, {}, {}'.format(student.fullname(), student.tell_pet(), student.expecto_patronus()))