I'm new to Python, trying to understand OOP. In my program I want the user to be able to buy and sell stocks but I'm struggling to implement this feature. Sorry if the problem is trivial.
User class + its one object
class User:
def __init__(self, name, budget=None, stocks=None):
self.name = name
self.budget = budget or 1000
self.stocks = stocks or 0
def sell_stock(self):
if self.stocks != 0:
self.stocks -= 1
def buy_stock(self):
self.stocks += 1
u1 = User("Karin", stocks=9)
Stock class + its one object
class Stock:
def __init__(self, price, name, availability=None):
self.price = price
self.name = name
self.availability = availability or 1
s1 = Stock("200", "Netflix")
I want to write a method called buy_stock() that will do the following:
- u1.budget - s1.price
- u1.stocks += 1
- s1.availability -= 1
- will show the price and the name of the stock that the user has bought, therefore I will see a message f"{Karin} has bought {Netflix} stock for {200} dollars."
portfolioof stocks, not just a single number. You might need to use a collection (like adictorlist) to store each different type (using thenameof the stock as a uniquely identifying key) and the amount the user owns.