【发布时间】:2019-02-24 21:16:32
【问题描述】:
我对面向对象编程非常陌生,当我运行我的 main 方法时,我无法访问我的类中的项目。我的程序试图允许用户将商品价格添加到购物车,直到完成并打印商品数量和总数。
class CashRegister:
print("Welcome to shopping world!")
def __init__(self, price):
self.price = price
def addItem(self, price):
CashRegister.totalPrice = CashRegister.totalPrice + price
CashRegister.itemCount = CashRegister.itemCount + 1
@property
def getTotal(self):
return totalPrice
@property
def getCount(self):
return itemCount
def main():
selection = "Y"
while selection != "N":
selection = input("Would you like to add another item to the
cart Y or N")
selection = selection.upper()
if selection == "Y":
price = input("What is the price of the item?")
CashRegister.addItem(price)
else:
print(CashRegister.getCount)
print(CashRegister.getTotal)
print(selection)
main()
这是我选择是时遇到的错误:
TypeError: addItem() missing 1 required positional argument: 'price'
这是我选择否时得到的输出:
Welcome to shopping world!
Would you like to add another item to the cart Y or Nn
<property object at 0x0000022CFFCA2598>
<property object at 0x0000022CFFCA2548>
N
【问题讨论】:
-
addItem 是一个 instance 方法,不清楚为什么要在 class 上调用它。
-
你应该打电话给
getTotaltotal。否则,您几乎可以只使用普通的 getter 方法。话虽如此,在您掌握了类的基础知识之前,您可能不应该使用属性。我建议看看official python tutorial on classes。它非常平易近人。自己完成动作并将示例输入到解释器中真的很好。 -
如果你想这样使用
addItem,你需要为addItem使用@staticmethod装饰器。检查此链接stackoverflow.com/questions/735975/static-methods-in-python
标签: python-3.x class object