定义投资组合类和局部全局变量错误

时间:2021-03-05 10:31:42

标签: python object-oriented-analysis

我需要用 Python 构建一个金融投资组合,我在这里引用了必要的部分来向您展示我遇到的错误:

import random

rand_s = random.uniform(0.5, 1.5)
    
class Portfolio:
    asset_type = 'portfolio'
    def __init__(self):
        self.cash = 0
        self.stocks = {}
        self.funds = {}
        self.transactions = []

    def buyStock(self, num_shares, Stock):        
        self.stocks[Stock.symbol] = num_shares
        self.cash -= num_shares*Stock.price
        self.transactions.append(f"{num_shares} shares of {Stock.symbol} added to the Stocks account.")
        return self.stocks

    def sellStock(self, sold_shares, Stock):
        if sold_shares == self.stocks[Stock.symbol]:
            self.stocks.pop(Stock.symbol)
            selling_price = rand_s*Stock.price
            self.cash += selling_price*sold_shares
            num_shares -= sold_shares
        elif sold_shares < self.stocks[Stock.symbol]:
            selling_price = rand_s*Stock.price
            self.cash += selling_price*sold_shares
            num_shares -= sold_shares

当我应用代码时:

portfolio.sellStock(2, s)

它给了我错误:

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-26-535e5b564024> in <module>
----> 1 portfolio.sellStock(2, s)

<ipython-input-14-71750cc18cc3> in sellStock(self, sold_shares, Stock)
     56             selling_price = rand_s*Stock.price
     57             self.cash += selling_price*sold_shares
---> 58             num_shares -= sold_shares
     59 
     60     def sellMutualFund(self, percentage_share, MutualFund):

UnboundLocalError: local variable 'num_shares' referenced before assignment

我该如何处理?如果有人能帮助我,我会很高兴。

0 个答案:

没有答案
相关问题