如何在字典中包含类的实例列表?

2024-10-03 23:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个具有以下属性、方法和实例的自定义类:

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')

现在我想创建一个字典来存储类向导的实例

hogwarts = {harry, ron, hermione, malfoy}

但是,作为输出,我得到的结果如下:

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

相反,我希望字典打印出实例中存储的信息。 我该怎么做


Tags: 实例selfformatreturnobjectmaindefat
3条回答

将表示添加到类函数中

def __repr__(self):
    print(f"First : {self.first }, Last : {self.last} ....")

可以将__repr____str__方法放置在类中,并使其返回打印对象时希望打印出的内容

例如:

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}.'

您需要使用self来使用类属性

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!")

你的字典实际上是一本set。您可以将实例放在一个list中,并在其中迭代以打印您认为合适的值,如下所示:

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

相关问题 更多 >