我正在嘗試列印所有專案,但出現錯誤:
TypeError: float() argument must be a string or a number, not 'NoneType'
我不知道為什么它會給出這個錯誤。
我使用 float 表示價格,使用 int 表示數量,因為它默認初始化為字串,這將給出另一個錯誤,因為不允許字串作為價格和數量的輸入。
import csv
class Item:
pay_rate = 0.8 # The pay rate after 20% discount
all = []
def __init__(self, name: str, price: float, quantity=0):
# Run validations to the received arguments
assert price >= 0, f"Price {price} is below 0!"
assert quantity >= 0, f"Price {price} is below 0!"
# Assign to self object
self.name = name
self.price = price
self.quantity = quantity
# Actions 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 instantiate_from_csv(cls):
with open('items.csv', 'r') as f:
reader = csv.DictReader(f)
items = list(reader)
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})"
Item.instantiate_from_csv()
print(Item.all)
CSV 檔案:
name , price , quantity
"Phone" , 100 , 1
"Laptop" , 1000 , 3
"Cable" , 10 , 5
"Mouse" , 50 , 5
"Keyboard" , 75 , 5
uj5u.com熱心網友回復:
真實的是示例 csv 資料,因為專案的鍵名是“價格”(帶有空格)。
所以 item.get('price') 將回傳默認值None因為它不能匹配 'price'。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/433959.html
標籤:Python python-3.x CSV
