Currently, I am on an online crash course on python and I encountered a confusing code.
As shown below, it is a code that is designed to find out the number of cotton polo shirts.
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)
it is obvious that the number of cotton polo shirts is 4 and yet the code gives 10, the sum of the number of cotton polo and sweatpants, as the answer (which is considered a correct one actually).
My question is, shouldn't the polo.Stock_by_Material method only iterates elements in the dictionary in the instance "polo" instead of both "polo" and "sweatpants"? I mean "polo" and "sweatpants" are not even in the same class so how come the polo.Stock_by_Material method would count the amount of both classes?
Please forgive me if I made some stupid mistakes here. I am only 1 week into python without any prior programming experience. Many thanks!