为什么我的班级出现属性错误?

时间:2013-05-02 19:26:00

标签: python

以下编辑!

这是我的retail_item课程:

#RetailItem Class

class RetailItem:
    def __init__(self, desc, inventory, price):
        self.__desc=desc
        self.__inventory=inventory
        self.__price=price

#mutators
    def set_desc (self, desc):
         self.__desc=desc
    def set_inventory (self, inventory):
         self.__inventory=inventory
    def set_price (self, price):
         self.__price = price

#accessors
    def get_desc(self):
        return self.__desc
    def get_inventory(self):
        return self.__inventory
    def get_price(self):
        return self.__price

    def __str__(self):
        return 'Item Description:' + self.__desc, \
               '\tNumber of Units:' + self.__inventory, \
               '\tPrice: $' + self.__price

我的cash_register课程:

#CashRegister Class

class CashRegister:
    def __init__(self, purchase, total, show, clear):
        self.__purchase=purchase
        self.__total=total
        self.__show=show
        self.__clear=clear

#mutators
    def purchase_item(self, purchase):
        self.__purchase=purchase
    def get_total(self, total):
        self.__total=total
    def show_item(self, show):
        self.__show=show
    def clear(self, clear):
        self.__clear=clear

#accessors
    def acc_purchase(self):
        return self.__purchase
    def acc_total(self):
        return self.__total
    def acc_show(self):
        return self.__show
    def acc_clear(self):
        return self.__clear

最后我的节目:

import retail_item
import cash_register

SHOW = 1
PURCHASE = 2
CART = 3
TOTAL = 4
EMPTY = 5
QUIT = 6

def main():
    mylist = make_list()
    #mycr = cash_register.CashRegister(mylist)

    choice = 0

    # Process menu selections until user quits program.
    while choice != QUIT:
        # Get the user's menu choice.
        choice = get_menu_choice()
        # Proces the choice.
        if choice == SHOW:
            show_items(mylist)
        elif choice == PURCHASE:
            purchase_item(mylist)
        elif choice == TOTAL:
            get_total(mylist)
        elif choice == EMPTY:
            clear(mylist)

def make_list():
    item_list = {}

    desc = 'Jacket'
    inventory = 12
    price = 59.95
    entry = retail_item.RetailItem(desc, inventory, price)
    item_list[desc]=entry

    desc = 'Jeans'
    inventory = 40
    price = 34.95
    entry = retail_item.RetailItem(desc, inventory, price)
    item_list[desc]=entry

    desc = 'Shirt'
    inventory = 20
    price = 24.95
    entry = retail_item.RetailItem(desc, inventory, price)
    item_list[desc]=entry

    return item_list

# The get_menu_choice function displays the menu and gets
#   a validated choice from the user.
def get_menu_choice():
    print()
    print('CASH REGISTER MENU')
    print('-------------------------')
    print('1. Show Retial Items')
    print('2. Purchase Item(s)')
    print('3. Show Current Shopping Cart')
    print('4. Show Total of Items Purchased')
    print('5. Empty Your Shopping Cart')
    print('6. Quit the program')
    print()

    # Get the user's choice.
    choice = int(input('Enter your choice: '))

    # Validate the choice.
    while choice < SHOW or choice > QUIT:
        choice = int(input('Enter a valid choice: '))

    # Return the user's choice.
    return choice

def show_items(mylist):
    print('\t\tDescription\t\tUnits in Inventory\t\tPrice')
    print('--------------------------------------------------------------------------------')
    x=1
    for item in mylist:
        print('Item #', x, '\t\t', item.get_desc(), '\t\t\t\t', item.get_inventory(), '\t\t\t$', format(item.get_price(), ',.2f'),sep='')
        print()
        x+=1

def purchase_item(mylist):
    desc = input('Enter the item you wish to purchase: ')
    if desc in mylist:
        amount=int(input('How many would you like to buy: '))
        if mylist[units]>0:
            mylist[units]-=amount
        elif (units-amount<0):
            mylist[units]=0
        else:
            mylist[units] = 0

    entry=cash_register.CashRegister(desc, units,)
    mylist[desc]=entry
    print()


def get_total(mylist):
    print()

def clear(mylist):
    print(mylist)
    mylist.clear()
    print(mylist)
main()            

所以我的问题是,如何只更新一个类的一个对象? 我如何调用cash_register类?

以下是分配的说明,如果有帮助的话:

本练习假设您已为Programming创建了RetailItem类 练习5.创建可与RetailItem类一起使用的CashRegister类。该 CashRegister类应该能够在内部保留RetailItem对象的列表。该 class应该有以下方法: •名为purchase_item的方法,它接受RetailItem对象作为参数。 每次调用purchase_item方法时,传递为的RetailItem对象 应该在列表中添加一个参数。 •名为get_total的方法,返回所有RetailItem对象的总价 存储在CashRegister对象的内部列表中。 •名为show_items的方法,显示有关存储的RetailItem对象的数据 在CashRegister对象的内部列表中。 •名为clear的方法,应清除CashRegister对象的内部列表。 在允许用户选择多个的程序中演示CashRegister类 购买物品。当用户准备结账时,程序应显示一个列表 他或她选择购买的所有物品以及总价格。

编辑: 这是我的最终代码。我知道它不漂亮,我为缺乏评论而道歉。我仍然会喜欢一些反馈,即使我很快会提交它(为了我自己的改善和工作机会!)这里是:

import retail_item
import cash_register

SHOW = 1
PURCHASE = 2
TOTAL = 3
EMPTY = 4
QUIT = 5

def main():
    #set all variables to zero
    lister = []
    inv=[]
    cost=[]
    desc=''
    inventory=0
    price=0
    total=0
    purchase=0
    #setting variable for each class
    cash=cash_register.CashRegister(purchase, total, lister, inv, cost)
    retail=retail_item.RetailItem(desc, inventory, price)

    #classes
    desc = 'Jacket'
    inventory = 12
    price = 59.95
    #setting classes
    retail.set_desc(desc)
    retail.set_inventory(inventory)
    retail.set_price(price)
    #Adding to cart
    cash.purchase_item(retail.get_desc(), lister)
    cash.purchase_item(retail.get_inventory(), inv)
    cash.purchase_item(retail.get_price(), cost)

    desc = 'Jeans'
    inventory = 40
    price = 34.95
    retail.set_desc(desc)
    retail.set_inventory(inventory)
    retail.set_price(price)
    cash.purchase_item(retail.get_desc(), lister)
    cash.purchase_item(retail.get_inventory(), inv)
    cash.purchase_item(retail.get_price(), cost)

    desc = 'Shirt'
    inventory = 20
    price = 24.95
    retail.set_desc(desc)
    retail.set_inventory(inventory)
    retail.set_price(price)
    cash.purchase_item(retail.get_desc(), lister)
    cash.purchase_item(retail.get_inventory(), inv)
    cash.purchase_item(retail.get_price(), cost)

    choice = 0

    # Process menu selections until user quits program.
    while choice != QUIT:
        # Get the user's menu choice.
        choice = get_menu_choice()
        # Proces the choice.
        if choice == SHOW:
            show_items(cash, retail, lister, inv, cost)
        elif choice == PURCHASE:
            purchase_item(cash, retail, lister, inv, cost)
        elif choice == TOTAL:
            get_total(cash, retail, lister)
        elif choice == EMPTY:
            price=0
            cash.set_total(price)
            clear(cash, lister)


# The get_menu_choice function displays the menu and gets
#   a validated choice from the user.
def get_menu_choice():
    print()
    print('CASH REGISTER MENU')
    print('-------------------------')
    print('1. Show Retail Items')
    print('2. Purchase Item(s)')
    print('3. Show Total of Items Purchased')
    print('4. Empty Your Shopping Cart')
    print('5. Quit the program')
    print()

    # Get the user's choice.
    choice = int(input('Enter your choice: '))

    # Validate the choice.
    while choice < SHOW or choice > QUIT:
        choice = int(input('Please enter a valid choice: '))

    # Return the user's choice.
    return choice

def show_items(cash, retail, lister, inv, cost):
    print('\t\tDescription\t\tUnits in Inventory\t\tPrice')
    print('--------------------------------------------------------------------------------')
    cash.show_item(lister, inv, cost)


def purchase_item(cash, retail, lister, inv, cost):

    JACKET=1
    JEANS=2
    SHIRT=3
    QUIT=4
    choice=0

    print()
    print('WHICH WOULD YOU LIKE TO BUY')
    print('-------------------------')
    print('1. Jacket')
    print('2. Jeans')
    print('3. Shirt')
    print('4. Quit')
    print()

    print('Choose as many as you like. Press 4 then ENTER to quit.')
    while choice != QUIT:
        # Get the user's menu choice.
        choice = int(input('Which would you like to buy: '))
        if choice < JACKET or choice > QUIT:
            choice = int(input('Please enter a valid choice: '))

        while choice != QUIT:
            # Proces the choice.
            if choice == JACKET:
                desc = 'Jacket'
                inventory = 12
                price = 59.95
                retail.set_desc(desc)
                retail.set_inventory(inventory)
                retail.set_price(price)
                cash.purchase_item(retail.get_desc(), lister)
                cash.purchase_item(retail.get_inventory(), inv)
                cash.purchase_item(retail.get_price(), cost)
                cash.set_total(price)
                break
            elif choice == JEANS:
                desc = 'Jeans'
                inventory = 40
                price = 34.95
                retail.set_desc(desc)
                retail.set_inventory(inventory)
                retail.set_price(price)
                cash.purchase_item(retail.get_desc(), lister)
                cash.purchase_item(retail.get_inventory(), inv)
                cash.purchase_item(retail.get_price(), cost)
                cash.set_total(price)
                break
            elif choice == SHIRT:
                desc = 'Shirt'
                inventory = 20
                price = 24.95
                retail.set_desc(desc)
                retail.set_inventory(inventory)
                retail.set_price(price)
                cash.purchase_item(retail.get_desc(), lister)
                cash.purchase_item(retail.get_inventory(), inv)
                cash.purchase_item(retail.get_price(), cost)
                cash.set_total(price)
                break

    print()


def get_total(cash, retail, lister):    
    print()
    cash.show_items(cash.get_list(lister))
    print('Your total is: $', format(cash.cost_total(),',.2f'))

def clear(cash, lister):
    print('Shopping cart emptied.')
    lister=lister.clear()
    price=0
    cash.set_total(price)

    return lister
main()

RetailItem类:

class RetailItem:
    def __init__(self, desc, inventory, price):
        self.__desc=desc
        self.__inventory=inventory
        self.__price=price

#mutators
    def set_desc (self, desc):
        self.__desc=desc
    def set_inventory (self, inventory):
        self.__inventory=inventory
    def set_price (self, price):
        self.__price = price

#accessors
    def get_desc(self):
        return self.__desc
    def get_inventory(self):
        return self.__inventory
    def get_price(self):
        return self.__price

    def __str__(self):
        return 'Item Description:' + self.__desc, \
              '\tNumber of Units:' + self.__inventory, \
              '\tPrice: $' + self.__price

最后,我的CashRegister类:

#CashRegister Class

class CashRegister:
    def __init__(self, purchase, total, lister, inv, cost):
        self.__purchase=purchase
        self.__total=total
        self.__lister=[]
        self.__inv=[]
        self.__cost=[]


#mutators
    def purchase_item(self, purchase, lister):
        self.__purchase=purchase
        lister.append(purchase)
        return lister

    def set_total(self, price):
        self.__total+=price


    def show_item(self, lister, inventory, price):
        i=0
        while i<len(lister):
            s=('Item # %i\t%s\t\t\t\t%i\t\t\t%4.2f') % ((i+1),lister[i],inventory[i],price[i])
            s = s.strip(' \t\n\r')
            print(s)
            i+=1

    def show_items(self, lister):
        i=0
        print('You have purchased the following items')
        while i<len(lister):
            print(lister[i])
            i+=1

    def clear(self, lister):
        i=0
        while i<len(lister):
            del lister[i]
            i+=1
            return lister

    def get_list(self, lister):
        return lister
#accessors
    def acc_purchase(self):
        return self.__purchase
    def cost_total(self):
        return self.__total
    def acc_show(self):
        return self.__show
    def acc_clear(self):
        return self.__clear

再次感谢你们!我经常使用这个网站,虽然我没有使用你们这次给我的很多东西,但你仍然很棒!

1 个答案:

答案 0 :(得分:2)

此代码存在几个主要问题。没有堆栈跟踪我不能确切地说你为什么会得到一个AttributeError,但我可以告诉CashRegister对象不能被实例化为写入。它的__init__指的是不存在的变量 - 项和项。

您的CashRegister类正在为__init__提供不必要的参数 - 在某些情况下应该是方法。我没有看到任何理由你的CashRegister类应该采用任何__init__参数 - 它应该初始化RetailItem对象的列表,并且可能是一个正在运行的总计,不做任何其他事情。 purchase_item应该更新这些内部属性,get_total和show_items应该读取它们(或者get_total应该根据列表计算总数,如果你没有保持运行总计)并且clear应该重置它们。

在风格上,mutators和accessors以及隐藏的内部数据不是Pythonic习语。通常,Python类直接获取和设置成员数据,并在行为需要更改时重构以使用属性。我看到这是一个课/练习,所以你可能正在使用它们,因为它们是必需的,但如果没有,你最好没有它们。

修改

这是我的main()的样子,使最小的编辑显示逻辑:

def main():
    items = make_list()
    mycr = cash_register.CashRegister()
    # at this point, mycr.show_items() should return [] and mycr.get_total() should return 0
    choice = 0
    while choice != QUIT:
        choice = get_menu_choice()
        if choice == SHOW:
            mycr.show_items()
        elif choice == PURCHASE:
            item, quantity = get_purchase(items)
            if item and quantity:
                item.set_inventory(max(0, item.get_inventory() - quantity))
                mycr.purchase_item(item, quantity)
        elif choice == TOTAL:
            print(mycr.get_total())
        elif choice == EMPTY:
            mycr.clear()

def get_purchase(items):
    desc = input('Enter the item you wish to purchase: ')
    if desc in items:        
        amount=int(input('How many would you like to buy: '))
        return items[desc], amount
    else:
        return None, 0

这并未涵盖所有可能性 - 例如,与原始代码一样,除了将数量设置为0之外,它允许输入比当前可用的更高的数量而没有副作用。但是练习描述没有提到库存跟踪,所以也许这不是一个要求。