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

时间:2020-07-12 23:10:34

标签: python class oop finance self

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))

请帮忙吗?

2 个答案:

答案 0 :(得分:2)

您可能要创建一个列表。当您有大量相似的变量难以命名和分配时,列表很有用。我对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,其中附带了可以在浏览器中运行的示例。

答案 1 :(得分:1)

由于您在以下位置附加了变量 investment self.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))