簡體   English   中英

代碼在錯誤的 class 中尋找屬性

[英]Code is looking for attributes in the wrong class

這段代碼真的沒有完成,但它已經到了那里。 我正在嘗試將項目名稱和價格的輸入組織到列表中,但由於代碼在項目 class 而不是收據 class 中查找 _purchases 屬性而導致錯誤。 這是什么原因造成的?

import datetime

class Item:
    def __init__(self,_name="None",_price=0,_taxable="no"):
        self._name=_name
        self._price=_price
        self._taxable=_taxable
    def __str__(self):
        base="{:-<20}".format(self._name)+"{:->20}".format(self._price)
        return base
    def getPric(self):
        pass
    def getTax(self):
        pass

class Receipt:
    def __init__(self,_tax_rate=0,_purchases=""):
        self._tax_rate=_tax_rate
        self._purchases=_purchases
    def __str__(self):
        pass
    def additem(self):
        list=self._purchases.append(self)
        
#Main Program
if __name__=="__main__":
    loop="no"
    print("Welcome to Receipt Creator")
    while True:
        name=input("Enter Item name: ")
        price=float(input("Enter Item Price: "))
        taxable=input("Is the item taxable (yes/no): ")
        product=Item(name,price,taxable)
        print(product)
        print(Receipt.additem(product))
        print(list)
        loop=input("Add another item (yes/no): ")
        if loop=="yes":
            continue
        else:
            break
    print("----- Receipt",str(datetime.datetime.now()),"-----")
    print(list)

編輯:這是錯誤

Traceback (most recent call last):
  File "C:\Users\lucas\Desktop\main.py", line 35, in <module>
    print(Receipt.additem(product))
  File "C:\Users\lucas\Desktop\main.py", line 23, in additem
    list=self._purchases.append(self)
AttributeError: 'Item' object has no attribute '_purchases'

您對自己擁有的東西有一個清晰的認識,但執行力還有很大的改進空間。

讓我們不要碰Item class,因為這不是造成麻煩的那個。 但是關於Receipt ,讓我們創建一個purchases列表來保存購買,讓我們定義一個方法( add_item )來填充該列表:

class Receipt:
    def __init__(self, tax_rate=0):
        self.tax_rate = tax_rate
        self.purchases = []

    def add_item(self, item):
        self.purchases.append(item)

現在,您肯定需要實例化該Receipt class (與您所做的相反),因此在您的主循環中您應該具有以下內容:

if __name__=="__main__":
    print("Welcome to Receipt Creator")
    rcpt = Receipt()
    while True:
        name = input("Enter Item name: ")
        price = float(input("Enter Item Price: "))
        taxable = input("Is the item taxable (yes/no): ")
        product = Item(name, price, taxable)
        print(product)
        rcpt.add_item(product)
        print(rcpt.purchases)
        loop = input("Add another item (yes/no): ")
        if loop == "yes":
            continue
        else:
            break
    print(rcpt.purchases)

現在,在您之前的代碼中需要注意一些事項:

  • 除非您想讓其他人知道某個屬性只能在 class 的定義中使用,否則實際上不需要使用前導下划線來命名屬性。
  • 您試圖打印list 請記住, list是內置的 class,因此請嘗試使用不同的名稱命名您的屬性(實際上,您可以使用尾隨下划線。就像list_ )。 此外,您試圖打印您在additem()方法中定義的list屬性,而沒有實例化Receipt class 並詢問 class (類似於instance.list_ )。
  • 在您定義的Receipt class 的__init__方法中,您的_purchases的默認值為"" (一個空字符串),但該屬性旨在成為一個列表。 (因為您試圖在additem()方法之后使用append()方法),這根本沒有意義。

@revliscano 有一個可以解決您的問題的答案。 我會把答案留給他。 我只是要解釋為什么你得到了你得到的有點令人困惑的錯誤。

在項目 class 中尋找 _purchases 屬性

在您的 class Receipt中,您有:

class Receipt:
    ...
    def additem(self):
        list=self._purchases.append(self)

后來用:


        product=Item(name,price,taxable)
        print(product)
        print(Receipt.additem(product))

因此,您在Receipt class 上調用additem() ,而不是在該 class 的實例上調用。 通常當你調用一個實例方法時,你調用它的實例是由 python 作為self傳入的。 It did not have an instance since you called it on the class itself, and as a result under the hood python was passing the product in as the self variable because python was treating it like a call on a static class method though it was supposed to是一個實例方法(即沒有clsself arg,只需將給定的 arg 傳遞給方法)。 因此,因為您像Receipt.additem(product)一樣調用它,所以product作為self傳遞。

這意味着當它嘗試執行self._purchases.append(self)時,就像它正在嘗試執行product._purchases.append(product)一樣,因此它試圖在product上找到_purchases屬性。 由於productItem class 的一個實例,這就是您獲得令人困惑的錯誤消息的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM