如何验证用户输入并验证正确应用的属性?

问题描述 投票:0回答:1

我正在编写一个可以检查各种事情的代码。 代码中的所有内容都工作正常,除了根据我的导师的说法,有两项检查失败了,而且我没有看到哪里出错了。 有人可以看一下并指出我正确的方向吗?

Tests that an ItemToPurchase can be given a name "Chocolate Chips", a price $3, and a quantity 1.
Your output
Item 1
Enter the item name:
2:Unit test
0 / 1
Tests that default constructor initializes attributes correctly.
Your output
Item 1
Enter the item name:

这是我使用的代码,但我不知道测试它是否可以给出名称或构造函数是否正确初始化属性意味着什么。

# Type code for classes here

class ItemToPurchase:

    def __init__(self):
        self.item_name = "None"
        self.item_price = 0
        self.item_quantity = 0
    def print_item_cost(self):
        print(self.item_name)
        print(self.item_quantity)

if __name__ == "__main__":

    item_name = 'Enter the item name:'
    item_price = 'Enter the item price:'
    item_quantity = 'Enter the item quantity:'


# Type main section of code here
# Item 1
print('Item 1')
item1_name = input('Enter the item name:\n')
item1_price = int(input('Enter the item price:\n'))
item1_quantity = int(input('Enter the item quantity:\n\n'))

#Item 2
print('Item 2')
item2_name = input('Enter the item name:\n')
item2_price = int(input('Enter the item price:\n'))
item2_quantity = int(input('Enter the item quantity:\n\n'))

#Combined Total
combined_total = (item1_price * item1_quantity) + (item2_price * item2_quantity)

#Outputs
print ('TOTAL COST')
print ('{} {} @ ${} = ${}'.format(item1_name, item1_quantity, item1_price, item1_price * item1_quantity))
print ('{} {} @ ${} = ${}\n'.format(item2_name,item2_quantity , item2_price, item2_price * item2_quantity))
print ('Total: ${}'.format(combined_total))

我不确定该怎么办,已经玩了几天了。

python constructor attributes
1个回答
0
投票

我终于明白了。 这是我完成的代码。

    class ItemToPurchase:

    def __init__(self):
        self.item_name = 'none'
        self.item_price = 0
        self.item_quantity = 0
    def print_item_cost(self):
        return '{} {} @ ${} = ${}'.format(self.item_name,self.item_quantity, self.item_price, (self.item_quantity * self.item_price))
if __name__ == "__main__":
    item1 = ItemToPurchase()
    print('Item 1')
    name = input('Enter the item name:\n')
    price = int(input('Enter the item price:\n'))
    quantity = int(input('Enter the item quantity:\n\n'))
    item1.item_name = name
    item1.item_price = price
    item1.item_quantity = quantity

    item2 = ItemToPurchase()
    print('Item 2')
    name = input('Enter the item name:\n')
    price = int(input('Enter the item price:\n'))
    quantity = int(input('Enter the item quantity:\n\n'))
    item2.item_name = name
    item2.item_price = price
    item2.item_quantity = quantity

    total_cost = (item1.item_price * item1.item_quantity) + (item2.item_price * item2.item_quantity)
    print('TOTAL COST')
    print(item1.print_item_cost())
    print(item2.print_item_cost())
    print()
    print ('Total: ${}'.format(total_cost))
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.