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>}
相反,我希望字典打印出存储在实例中的信息。我怎样才能做到这一点?
解决方案
将表示添加到您的类函数。
def __repr__(self):
print(f"First : {self.first }, Last : {self.last} ....")
推荐阅读
- alexa - 我们可以让Alexa在给定时间后像警报一样说出一句话吗?
- javascript - 如何从图像源字符串中获取源的一部分?
- pipeline - snakemake 总是在第 44 行报告“ MissingOutputException,5 秒后丢失文件:
- crystal-reports - 合并水晶报表组内的数据
- php - 我想在考试结果中显示第 1、第 2、第 3 的位置
- python - 与日期时间索引条件合并
- node.js - 来自节点 js 中 HTTPS 安装的问题
- aws-lambda - AWS Java Lambda 压缩 JSON 响应失败:“由于配置错误,执行失败:格式错误的 Lambda 代理响应”
- colors - 索引颜色内存大小与原始图像
- java - 使用深度优先搜索迭代回溯