gpt4 book ai didi

python - 如何在 python 中检索字典中的类对象?

转载 作者:行者123 更新时间:2023-12-01 11:38:49 25 4
gpt4 key购买 nike

我已经成功地在字典中添加了一个员工类对象。但是我无法从同一个字典中取回值?下面是代码和输出。

源代码:

# decalre a dict
employee_collection = {}

# Class object to store employee's details
class employee:
# Constructor
def __init__(self,name,age):
self.name = name
self.age = age

# Display the object values
def print_property(self):
print(f"name is {self.name} and age is {str(self.age)}")

# loop to add multiple employee details
for x in range(1, 6):
obj= employee("xxx", 28+x)
employee_collection.update({x : obj})

# extract the employee detail from and print the vaue to user
for x in employee_collection:
# print(x.name)
print(x)

print(employee_collection)

输出:

1
2
3
4
5
{1: <__main__.employee object at 0x0327F610>, 2: <__main__.employee object at 0x03550C70>, 3: <__main__.employee object at 0x03550580>, 4: <__main__.employee object at 0x035503B8>, 5: <__main__.employee object at 0x03550FB8>}

我的问题是:如何在 main 方法中使用循环打印姓名和年龄?

最佳答案

两种方法。 dict 正在存储每个 employeeinstance(顺便说一句,应该是 Employee)。

您可以打印实例的属性,或者更改尝试打印对象时发生的情况。

前者:

for key, e in employee_collection.items():
print(f'{x} {e.name} {e.age}')

后者:

class Employee:
...

def __str__(self):
return f'{self.name} {self.age}'


for e in employee_collection.values():
print(e)

关于python - 如何在 python 中检索字典中的类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59999412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com