instantiate_from_csv类方法应该从名为“items.csv”的CSV文件中读取数据,为文件中的每行数据创建新的Item对象,并将对象添加到all列表中。然后遍历字典列表并创建新的Item
**对象,但由于价格和数量应该是浮点数和整数,我用float()和int()方法转换它们,但我有一个错误
下面是错误:
price=float(item.get('price')),
^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: float() argument must be a string or a real number, not 'NoneType'
下面是代码:
import csv
class Item:
pay_rate = 0.8
all = []
def __init__(self, name: str, price: int , quantity: int):
#run validation to the received arguments
assert quantity >= 0, "The {quantity} quantity should be greater or equal to zero"
assert price >= 0, "The price should be greater or equal to zero"
#assigned to the self object
self.name = name
self.price = price
self.quantity = quantity
#Action to execute
Item.all.append(self)
def calculate_total_price(self):
return self.price * self.quantity
def apply_discount(self):
self.price = self.price * self.pay_rate
@classmethod
def intantiate_from_csv(cls):
with open('items.csv', 'r') as f:
reader = csv.DictReader(f)
items = list(reader)
# print(items)
for item in items:
Item(
name=item.get('name'),
price=float(item.get('price')),
quantity=int(item.get('quantity')),
)
def __repr__(self):
return f"Item('{self.name}', {self.price}, {self.quantity})"
# items
Item.intantiate_from_csv()
print(Item.all)
1条答案
按热度按时间5kgi1eie1#
我有这个错误是因为在标题中的逗号后面有多余的空格。删除多余的空格解决了这个错误