0

目前,我正在上一个关于 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,没有任何编程经验。非常感谢!

4

4 回答 4

1

您正在按材料(棉花)进行聚合。衬衫和运动裤类的材质属性都设置为棉。因此,有 10 个棉花项目,这就是您在最后展示的内容。

如果要按项目聚合,可以按如下所示进行。

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
   def Stock_by_item(self, name):
     count=0
     n=0
     for rec in Clothing.stock['name']:
       if rec == name:
         count += Clothing.stock['amount'][n]
         n+=1
     return count

class shirt(Clothing):
   material="Cotton"

class pants(Clothing):
   material="Cotton"

polo = shirt("Polo")
other_polo_shirts = shirt("Polo")

sweatpants = pants("Sweatpants")
polo.add_item(polo.name, polo.material, 4)
other_polo_shirts.add_item(other_polo_shirts.name, other_polo_shirts.material, 16)

sweatpants.add_item(sweatpants.name, sweatpants.material, 6)
current_stock = polo.Stock_by_item("Polo")
print(current_stock)
于 2020-06-18T12:51:05.787 回答
0

如果我没看错你的问题,

stockstaticClothing 类的变量。这个的任何子类都将共享这个变量。

因此,polo 和运动裤共享同一个字典。

希望这会有所帮助。

于 2020-06-18T12:55:46.877 回答
0

正如@Sagi 提到的,它返回所有棉花库存,因为它在对象及其子类stock之间共享。Cloathing但是,您的困惑是合理的,因为此代码违反了单一责任原则,库存不应成为 Clothing 类的一部分。

于 2020-06-18T12:58:19.077 回答
0

萨吉是正确的。Stock_by_Material 函数还需要检查“名称”以确保它是“Polo”,然后才将其添加到计数中。你没有错过任何东西,课程的制作者只是犯了一个错误。

于 2020-06-18T12:59:42.837 回答