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'