python - 如何构建一个通用函数来打印 Python 3.3 中先前列表的属性列表?

标签 python python-3.x generic-list generic-programming generic-collections

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

我的目标是构建一个通用函数来打印先前列表的属性列表(在本示例中是图书列表及其属性 1:标题或流派或价格)。我可以在 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'

最佳答案

改变

print(i.attribute)

print(getattr(i, attribute)) 
#or if you want to specify a default, 
#print(getattr(i, attribute, ''))

由于attribute是一个参数,因此您需要使用getattr提取对象的属性。而不是仅仅执行i.attribute

关于python - 如何构建一个通用函数来打印 Python 3.3 中先前列表的属性列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19433833/

相关文章:

python - 如何解压 df 中的列表并在该列表上使用加法而不进行循环

python - 如何在 Mac OS X 上将 py 扩展与 python 启动器相关联?

python - 你如何让 VSCode 中的 pylint 知道它在一个包中(以便相对导入工作)?

.net - 从通用列表中获取最大和更大的对象

c# - 将通用列表转换为 BindingList<T>

python - 保存带有时间戳的视频帧

python - 从 python 中的嵌套 JSON 文件访问值

python - for 循环中未使用的变量

python - 无法在 TransientModel odoo 11 中获取产品

java - "? extends ParentClass"使只读?