目前,我正在上一个关于 python 的在线速成课程,我遇到了一个令人困惑的代码。
如下图所示,是一个专门用来查出棉质polo衫数量的代码。
class Clothing:
stock={ 'name': [],'material' :[], 'amount':[]}
def __init__(self,name):
material = ""
self.name = name
def add_item(self, name, material, amount):
Clothing.stock['name'].append(self.name)
Clothing.stock['material'].append(self.material)
Clothing.stock['amount'].append(amount)
def Stock_by_Material(self, material):
count=0
n=0
for item in Clothing.stock['material']:
if item == material:
count += Clothing.stock['amount'][n]
n+=1
return count
class shirt(Clothing):
material="Cotton"
class pants(Clothing):
material="Cotton"
polo = shirt("Polo")
sweatpants = pants("Sweatpants")
polo.add_item(polo.name, polo.material, 4)
sweatpants.add_item(sweatpants.name, sweatpants.material, 6)
current_stock = polo.Stock_by_Material("Cotton")
print(current_stock)
很明显,棉 Polo 衫的数量是 4,但代码给出了 10,即棉 Polo 衫和运动裤的数量之和,作为答案(实际上被认为是正确的)。
我的问题是,polo.Stock_by_Material 方法不应该只在实例“polo”而不是“polo”和“sweatpants”中迭代字典中的元素吗?我的意思是“马球”和“运动裤”甚至不在同一个班级,那么 polo.Stock_by_Material 方法怎么会计算两个班级的数量呢?
如果我在这里犯了一些愚蠢的错误,请原谅我。我只有 1 周的时间进入 python,没有任何编程经验。非常感谢!