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'))
제 목표는 이전 목록 (이 예에서는 책 목록이고 속성 중 하나는 제목 또는 장르 또는 가격)에 대한 속성 목록을 인쇄하는 제네릭 함수를 작성하는 것입니다. 파이썬 3.3에서 이것을 할 수 있습니까?Python 3.3에서 이전 목록의 속성 목록을 인쇄하는 제네릭 함수를 작성하는 방법은 무엇입니까?
보관할 점점 오류 : attribute
이후
print(getattr(i, attribute))
#or if you want to specify a default,
#print(getattr(i, attribute, ''))
이 매개 변수
print(i.attribute)
에
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'
속성 이름을 동적으로 사용하려는 경우 'dict'(또는 'dict'을 상속하거나 사용하는 클래스) 대신 'namedtuple'을 사용하는 이유는 무엇입니까? 'namedtuple'의 요점은 당신에게 _static_ 속성을주는 것입니다. 소스 코드에 이름을 붙임으로써 찾을 수 있습니다. – abarnert
또 어떤 이유에서'namedtuple'을 실제로 해체해야 할 필요가 있다면,'i_fields'라는 이름의 속성 명 목록에 언제나 액세스 할 수 있습니다. 아니면'i._asdict()'를 사용하여'OrderedDict'로 변환 할 수 있습니다. . – abarnert