python-mastery/stock.py
2023-10-27 16:53:01 -05:00

33 lines
807 B
Python

import csv
class Stock:
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
def cost(self):
return self.shares * self.price
def sell(self, num):
self.shares -= num
if self.shares < 0:
self.shares = 0
def read_portfolio(filename):
with open(filename) as f:
rows = csv.reader(f)
_ = next(rows)
return [Stock(row[0], row[1], row[2]) for row in rows]
def print_portfolio(portfolio):
headers = ("name", "shares", "price")
fmtstr = "{0: >10} {1: >10} {2: >10}"
print(fmtstr.format(*headers))
print("{0:->10} {1:->10} {2:->10}".format("", "", ""))
for stock in portfolio:
print(fmtstr.format(stock.name, stock.shares, stock.price))