【发布时间】:2013-10-17 17:55:00
【问题描述】:
from collections import namedtuple
Book = namedtuple('Book', 'author title genre year price instock')
BSI = [
Book("JK Rowling", "Harry Potter", "Fantasy", 1997, 10.00, 50),
Book("Harper Lee", "To Kill a Mockingbird", "Fiction", 1960, 15.00, 100),
Book("Dan Brown", "Da Vinci Code", "Thriller", 2003, 20.00, 500),
Book("Mr. Python", "How to Python", "Technology", 2010, 40.00, 10),
Book("Stephen King", "It", "Horror", 1986, 50.00, 10),
Book("Some Guy", "Time Traveling", "Technology", 2020, 800.00, 256)
]
def Book_collection_attribute (BSI: list, attribute: str) -> list:
'''Print out the list of the specific attribute of the list of Book collection'''
for i in BSI:
print(i.attribute)
return BSI
print(Book_collection_attribute(BSI,'title'))
我的目标是构建一个通用函数来打印前一个列表的属性列表(在此示例中是图书列表及其属性之一:标题或流派或价格)。我可以在 Python 3.3 中执行此操作吗?
不断报错:
Traceback (most recent call last):
File "C:\Users\ntt2k\Desktop\ICS 31\lab3.py", line 133, in <module>
print(Book_collection_attribute(BSI,'title'))
File "C:\Users\ntt2k\Desktop\ICS 31\lab3.py", line 131, in Book_collection_attribute
print(i.attribute)
AttributeError: 'Book' object has no attribute 'attribute'
【问题讨论】:
-
如果您尝试动态使用属性名称,为什么要使用
namedtuple而不仅仅是使用dict(或继承自dict或使用dict的类)?namedtuple的全部意义在于为您提供 static 属性,您可以通过在源代码中找到它们的名称来查找这些属性。 -
另外,如果您确实需要解构
namedtuple出于某种原因,您始终可以将其属性名称的有序列表访问为i_fields,或将其转换为OrderedDicti._asdict().
标签: python python-3.x generic-list generic-programming generic-collections