【问题标题】:Accessing items within a class in Python?在 Python 中访问类中的项目?
【发布时间】: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


【解决方案1】:

首先,您不要使用类名在其方法中声明变量:您有 self (您可以将其重命名为您喜欢的任何名称,但“self”是约定俗成的)

其次,你必须在 main 函数中初始化你的类对象,否则 Python 将不知道如何处理你调用的方法(当你在类中定义方法时,第一个参数 self 代表类对象,所以每次你初始化一个对象然后调用它的方法时,你在括号内传递的参数实际上是第二个参数,第一个是对象本身)

第三:这更像是一种风格的东西,但你并没有真正在python中使用CamelCase,除了类名,其余的都在snake_case中

第四个:+=example = example + 1 更易读、更快

class CashRegister(object) :

    def __init__(self) :
        self.total_price = 0
        self.item_count = 0

    def add_item(self, price) :
        self.total_price += int(price)
        self.item_count += 1

    def get_total(self) :
        return self.total_price

    def get_count(self) :
        return self.item_count

def main() :
    register = CashRegister()
    selection = True

    while selection :
        selection = input("Would you like to add another item to the cart Y or N\n\t").upper()

        if selection == "Y" :
            price = input("What is the price of the item?\n\t")
            register.add_item(price)

        else :
            print(register.get_total())
            print(register.get_count())
            print(selection)
            selection = False

main()

这就是我可能会这样做的方式,我已经取出了 @property 装饰器,因为我不知道你是否真的需要它们,你可以调用带有括号的方法 () at最终得到你想要的

然后,如果您真的想使用它,您应该做更多的事情,那就是异常捕获,如果将负值传递为price,则确定收银机的行为等等。 .. 祝你好运,享受 Python

【讨论】:

    【解决方案2】:

    你有很多错误需要在self中确定totalprice和itemcount,你需要用cashregister类确定一个变量

    class CashRegister:
        print("Welcome to shopping world!")
        def __init__(self):
            self.totalPrice=0
            self.itemCount=0
        def addItem(self, price):
            self.totalPrice = self.totalPrice + price 
            self.itemCount = self.itemCount + 1
        @property
        def getTotal(self):
            return self.totalPrice
        @property
        def getCount(self):
            return self.itemCount
    def main():
        selection = "Y"
        box=CashRegister()
        while selection != "N":
            selection = input("Would you like to add another item to thecart Y or N\n\t:")
            selection = selection.upper()
            if  selection == "Y":
                price = input("What is the price of the item?\n\t:")
                box.addItem(int(price))
            else:
                print(box.getCount)
                print(box.getTotal)
                print(selection)
    main()
    

    【讨论】:

    • 感谢那些帮助过的人。我想我糟糕的编程让我在这里得到了负分。艰难的人群。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多