An instance of a stock holding consisting of name, shares, and price.
| 1 | # stock.py |
| 2 | |
| 3 | class Stock: |
| 4 | ''' |
| 5 | An instance of a stock holding consisting of name, shares, and price. |
| 6 | ''' |
| 7 | __slots__ = ('name','_shares','price') |
| 8 | def __init__(self,name, shares, price): |
| 9 | self.name = name |
| 10 | self.shares = shares |
| 11 | self.price = price |
| 12 | |
| 13 | def __repr__(self): |
| 14 | return f'Stock({self.name!r}, {self.shares!r}, {self.price!r})' |
| 15 | |
| 16 | @property |
| 17 | def shares(self): |
| 18 | return self._shares |
| 19 | |
| 20 | @shares.setter |
| 21 | def shares(self, value): |
| 22 | if not isinstance(value,int): |
| 23 | raise TypeError("Must be integer") |
| 24 | self._shares = value |
| 25 | |
| 26 | @property |
| 27 | def cost(self): |
| 28 | ''' |
| 29 | Return the cost as shares*price |
| 30 | ''' |
| 31 | return self.shares * self.price |
| 32 | |
| 33 | def sell(self, nshares): |
| 34 | ''' |
| 35 | Sell a number of shares and return the remaining number. |
| 36 | ''' |
| 37 | self.shares -= nshares |