计算投资组合中的投资总额?

Calculate total sum of investments in Portfolio?

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)

我想要一个代码来计算代码中所有投资者的投资总规模,而不是手动输入 300:

portfolio = Portfolio('Smt', sum(100 + 150 + 50))

有什么帮助吗?

由于您在此处附加了变量 investmentself.investments.append(investment) 数组,您可以简单地使用 for 循环 迭代并获得投资总额,例如totalSum = 0(假设它是一个全局变量),因此:

totalSum = 0

for each in self.investments: #this for loop could be anywhere of your preference
        totalSum += each # will store the sum

portfolio = Portfolio('Smt', totalSum))

您可能想要创建一个列表。当您有大量相似的变量而命名和赋值变得很麻烦时,列表很有用。我在 Python 中包含了对列表的简单介绍,但您可能可以在 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 ]

如果您有兴趣更好地了解列表的功能,我建议您参考 W3Schools' Python Tutorial,其中包含您可以在浏览器中 运行 的示例。