【发布时间】:2015-09-24 00:26:37
【问题描述】:
我有一个名为 Books 的命名元组列表,我试图将 price 字段增加 20%,这确实会改变 Books 的值。我试着做:
from collections import namedtuple
Book = namedtuple('Book', 'author title genre year price instock')
BSI = [
Book('Suzane Collins','The Hunger Games', 'Fiction', 2008, 6.96, 20),
Book('J.K. Rowling', "Harry Potter and the Sorcerer's Stone", 'Fantasy', 1997, 4.78, 12)]
for item in BSI:
item = item.price*1.10
print(item.price)
但我不断得到:
Traceback (most recent call last):
print(item.price)
AttributeError: 'float' object has no attribute 'price'
我了解我无法在命名元组中设置字段。如何更新price?
我试着把它变成一个函数:
def restaurant_change_price(rest, newprice):
rest.price = rest._replace(price = rest.price + newprice)
return rest.price
print(restaurant_change_price(Restaurant("Taillevent", "French", "343-3434", "Escargots", 24.50), 25))
但我得到一个错误替换说:
rest.price = rest._replace(price = rest.price + newprice)
AttributeError: can't set attribute
谁能告诉我为什么会这样?
【问题讨论】:
标签: python list python-3.x tuples