class Investor:
def __init__(self,name,investment):
self.name = name
self.investment = investment
def get_investment(self):
return self.investment
class Portfolio:
def __init__(self,name, investments):
self.name = name
self.investments = []
#add investment object to list
def add_investment(self, investment):
self.investments.append(investment)
return True
def total_investments(self):
value = 0
for investment in self.investments:
value += investment.add_investment()
return value
s1 = Investor('John', 100)
s2 = Investor('Tim', 150)
s3 = Investor('Stacy', 50)
portfolio = Portfolio('Smt', 300)
portfolio.add_investment(s1)
portfolio.add_investment(s2)
print(portfolio.investments[0].investment)
Instead of inputing manually the 300, I want to have a code that will calculate the total size of the investments made by all of the investors in the code:
portfolio = Portfolio('Smt', sum(100 + 150 + 50))
Any help please?
You probably want to create a list. Lists are useful when you have a large number of similar variables that become tiresome to name and assign. I've included a quick-and-dirty introduction to lists in Python, but you can probably find better tutorials on Google.
investors = [ # Here we create a list of Investors;
Investor("John", 150), # all of these Investors between the
Investor("Paul", 50), # [brackets] will end up in the list.
Investor("Mary", 78)
]
# If we're interested in the 2nd investor in the list, we can access
# it by indexing:
variable = investors[1] # Note indexing starts from 0.
# If we want to add another element to the list,
# we can call the list's append() method
investors.append(Investor("Elizabeth", 453))
# We can access each investor in the list with a for-loop
for investor in investors:
print(investor.name + " says hi!")
# If we want to process all of the investors in the list, we can use
# Python's list comprehensions:
investments = [ investor.investment for investor in investors ]
If you're interested in getting a better overview of what is possible with lists, I would refer you to W3Schools' Python Tutorial which comes with examples you can run in your browser.