我做这个程序是为了计算一个假设商店里商品的总价格,最后我遇到了一个双重呼叫。避免双重呼叫的最佳方法是什么
#!/usr/bin/env python3
#Lukas Robin
#07.06.2021
class Stonk:
def __init__(self, name ='', price = '', quantity = '', total = 0, shirtTotal = 0, sockTotal = 0, jeanTotal = 0):
self.self = self
self.name = name
self.price = price
self.quantity = quantity
self.total = total
self.shirtTotal = shirtTotal
self.sockTotal = sockTotal
self.jeanTotal = jeanTotal
def main(__init__):
__init__.name = ""
__init__.total = 0
__init__.shirtTotal = 0
__init__.sockTotal = 0
__init__.jeanTotal = 0
__init__.price = {'shirts' : 25, 'socks': 12, 'jeans' : 50}
__init__.name = input("Are you buying shirts, socks and/or jeans? ")
def shirts(main, __init__):
__init__.quantity = int(input("How many shirts would you like? "))
__init__.shirtTotal = __init__.shirtTotal + (__init__.quantity*__init__.price['shirts'])
print("The price of the shirts is, "+ str(__init__.shirtTotal))
return __init__.shirtTotal
def socks(main, __init__):
__init__.quantity = int(input("How many socks would you like? "))
__init__.sockTotal = __init__.sockTotal + (__init__.quantity*__init__.price['socks'])
print("The price of the socks is, "+ str(__init__.sockTotal))
return __init__.sockTotal
def jeans(main, __init__):
__init__.quantity = int(input("How many jeans would you like? "))
__init__.jeanTotal = __init__.jeanTotal + (__init__.quantity*__init__.price['jeans'])
print("The price of the jeans is, "+ str(__init__.jeanTotal))
return __init__.jeanTotal
main(__init__)
options = __init__.name.split(", ")
shirtTotals = shirts(main, __init__)
sockTotals = socks(main, __init__)
jeanTotals = jeans(main, __init__)
for items in options:
if items == ('socks' or 'sock'):
socks(main, __init__)
elif items == ('shirts' or 'shirt'):
shirts(main, __init__)
elif items == ('jeans' or 'jean'):
jeans(main, __init__)
__init__.total = shirtTotals+sockTotals+jeanTotals
print("Your total is "+str(__init__.total))
(问题已经回答,感谢所有帮助过你的人。)
你的问题是:
不管
input("Are you buying shirts, socks and/or jeans? ")
的结果如何,都会调用shirts()
socks()
和jeans()
因此,我要做的第一个修复是删除
shirts
、socks
和jeans
的重复项因此,代码的底部如下所示:
即使有了这些修复,仍然存在对dunder方法的滥用
Dunder方法
Dunder方法或双下划线方法是一种特殊或神奇的方法,永远不会被直接调用。这方面的一个例子是
__init__
方法如果我们要创建一个新的Stonk对象,我们不直接调用
__init__
,而是调用Stonk(),那么python将在后台调用__init__
。这使代码更干净,因为我们没有在代码中散播init函数调用,而是看到了更清晰的Stonk()因此,我们必须将
__init__
从它不属于的每个地方移除相反,我们应该用引用当前对象的
self
替换它通过这些更改,您的代码将如下所示:
但我们有一个例外
AttributeError: 'Stonk' object has no attribute 'shirtTotals'
如果我们比较以下代码块,我们将:
以及:
我们可以看到
shirtTotals
与shirtTotal
不匹配,对于sockTotals
和jeanTotals
也存在同样的问题。这里的修正是将总计更改为总计我们可以做的另一个改进是从构造函数中取出读取输入。这是因为在构造函数中读取输入是不直观的。通过这两项改进,您的代码将如下所示:
用这些小补丁we can see your code running here
<强>我将考虑的编辑列表:
相关问题 更多 >
编程相关推荐