2

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
nonskill
  • 111
  • 1
  • 5

3 Answers3

2

Add a representation to your class function.

def __repr__(self):
    print(f"First : {self.first }, Last : {self.last} ....")
DKDK
  • 302
  • 2
  • 10
1

You could place the __repr__ or __str__ method inside the class, and make it return what you want to have printed out when you print the object.

An example would be:

def __repr__(self):
    return f'I am {self.first} {self.last}. I have a pet {self.pet}, its name is {self.petname}. My patronus is {self.patronus}.'
Epic Gamer
  • 101
  • 1
  • 10
1

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()))
James Tollefson
  • 883
  • 3
  • 14