我无法获得变量的结果

时间:2019-04-22 02:36:01

标签: python python-3.7

我正在尝试从名为“ Classes”的文件中检索getChangePercent(),并将其显示在名为“ StockTest”的文件中,但这并不能阻止我。

我可以在类文件的顶部声明变量ChangePercent,但不允许这样做。

为了使程序正常运行,我也不得不在顶部声明currentPricepreviousPrice

 symbol = ''
 name = ''

 class Stock():
 def __init__(self, symbol = '', name = '', previousClosingPrice = 20.5, currentPrice = 20.35):
      self.__symbol = symbol
      self.__name = name
      self.__previousClosingPrice = previousClosingPrice
      self.__currentPrice = currentPrice

 def getName(self):
      return self.__name

 def getSymbol(self):
      return self.__symbol

 def getPreviousPrice(self):
      previousClosingPrice = 20.5
      previousClosingPrice = self.__previousClosingPrice
      return self.__previousClosingPrice

 def getCurrentPrice(self):
      currentPrice = 20.35
      currentPrice = self.__currentPrice
      return self.__currentPrice

 def getChangePercent(self):
      ChangePercent = round(1 - currentPrice / PreviousClosingPrice, 2)
      self.__ChangePercent = ChangePercent
      return self.__ChangePercent

这是下面的StockTest代码。

from Classes import Stock

def main():

     stock1 = Stock('INTC', 'Intel Corporation', 20.5, 20.35) 
     print("The stock's symbol is", stock1.getSymbol())
     print("The stock's name is", stock1.getName())
     print("The stock was at", stock1.getPreviousPrice())
     print("The stock is now at", stock1.getCurrentPrice())
     print("The stock had a change of", stock1.getChangePercent())

main()

当我在“ Classes”文件的顶部声明变量时,会显示:

“库存变化了-0.01”

请记住,我无法像在第一组代码中对“ symbol”和“ name”所做的那样声明以前的价格和当前的价格。我实际上希望程序显示:

“股票的变动幅度为-1%”

请帮助!

1 个答案:

答案 0 :(得分:0)

正确的百分比格式{0:.0%}应该可以解决问题。

print("The stock had a change of {0:.0%}".format(stock1.getChangePercent()))
#The stock had a change of 1%