python-mastery/stock.py
2023-10-28 16:43:42 -05:00

35 lines
830 B
Python

import csv
from Decimal import Decimal
class Stock:
types = (str, int, float)
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
@classmethod
def from_row(cls, row):
values = [func(val) for func, val in zip(cls.types, row)]
return cls(*values)
def cost(self):
return self.shares * self.price
def sell(self, num):
self.shares -= num
if self.shares < 0:
self.shares = 0
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))