【问题标题】:how to setup an accumulator variable?如何设置累加器变量?
【发布时间】:2021-03-08 01:33:40
【问题描述】:

首先,我正在编写一个代码来从一个文件中打印宜家的库存,该文件具有这样的行, F,301.841.73,9.99,HOLMÖ,落地灯 - 提供柔和的氛围灯,,75,116,22,2.2

其中第三个“9.99”是该家具物品的价格。我也有价格变量的 getter 和 setter。

def setPrice(self, f_price):
    self.__price = f_price

def getPrice(self):
    return self.__price

主类 Furniture 和其他子类,如“BED”、“NIGHTSTAND”、“ARMCHAIR”等。

这些类有一个 UNIT 测试框架。在其中创建一个列表,他们打开文件并使用循环,它添加家具项目的所有变量,如类型、货号、价格、瑞典语名称、基本描述,以及家具类的颜色(可选)以及从子类到列表的子变量。

那么,最后,我们需要计算库存的总价值。我将 Total_value 变量初始化为 0。

total_value = 0

for furniture_item in inventory:
    print(str(furniture_item)) # print the item
    print("="*30) # print a separator
    # ADD THE PRICE OF THE ITEM TO THE ACCUMULATOR VARIABLE
    total_value += (value)

当我尝试从 getPrice 函数获取价格时:

price = Furniture.getPrice
    total_value += price

它给了我这样的错误:

*****Error***
Traceback (most recent call last):
  File "__tester__.python3", line 212, in <module>
      total_value += price
TypeError: unsupported operand type(s) for +=: 'int' and 'function'**

当我这样做时:

Furniture.getPrice = price
    total_value += price

它给了我**Total Inventory Value: 3184.0** 的值。但是,期望的值是**Total Inventory Value: 1432.91**,我不知道我做错了什么。

如果有人可以向我建议如何获得这个预期值,那就太好了!!!

【问题讨论】:

  • 什么是(value)
  • 我只是使用了与价格不同的名称,就是为了这个。

标签: python


【解决方案1】:

我猜你想要

total_price += furniture_item.getPrice()

【讨论】:

  • 非常感谢!!!有效。顺便说一句,你怎么知道的?我做错了什么?
  • 首先,getPrice 是一个函数,而您缺少括号(这是您的原始错误消息的来源)。其次,getPrice 是一个实例方法,所以你必须使用furniture_item 方法来获取它,而不是Furniture 类。
  • 哦,这就是我无法得到它的原因。那讲得通。我试图调用 getPrice 函数忘记了 furniturre.item 方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 2011-07-21
相关资源
最近更新 更多