Подсчитать общую сумму вложений в Портфель? - PullRequest
0 голосов
/ 13 июля 2020
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 ]

2 голосов
/ 13 июля 2020

Вероятно, вы захотите создать список . Списки полезны, когда у вас есть большое количество похожих переменных, которые становится утомительно называть и присваивать. Я включил краткое введение в списки в 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 голос
/ 13 июля 2020

Поскольку вы добавили сюда переменную investment : self.investments.append(investment) массив, вы можете просто использовать для l oop, чтобы выполнить итерацию и получить общую сумму инвестиций , например, 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))
...