Reputation: 59
I need to write a "store". I have class ClothingItem
-- Shoe
, Pant
and Shirt
all inherit from ClothingItem
. Now I'm working on class Inventory(list)
. I can add shoes and pants and shirts, and get a total count (inventory.len()
). Now Dad wants me to tell him how many shoes are in inventory, how many pants, whatever. He says that if my store starts selling Short
s or Legging
s, I'm not allowed to touch my Inventory
class. He said something about passing a TYPE to the length function, but I can't figure out how to ask Google that. He works in C# so he only knows how to do it in that, not in Python.
So... can someone PLEASE tell me where to look to figure this out? He said if you post code he'll know and just make me do something harder, so please don't send me code! Just tell me where I should look and I'll be super-awesome grateful.
Upvotes: 3
Views: 228
Reputation: 12819
There's a few ways you can tackle this problem. The first one that pops to mind is to use the isinstance
and filter
functions (or a list comprehension in place of filter
... but if you're just learning, comprehensions might be too much too soon) to pare down your list into just items that belong to a specific class.
Also, remind your dad that if learning programming is "killing you", he's created the wrong environment for you to learn. No one thrives in a topic when they feel that way. As someone who loves programming, it really makes me sad to see that happen to people.
Upvotes: 3
Reputation: 104050
If your class ClothingItem
includes a method like: in_stock()
that returns a string built from self.name
and self.quantity
, every subclass (Shoe
, Pant
, Shirt
, Legging
, etc.) just needs to assign self.name
correctly when it is instantiated.
What this does is provide something called polymorphism (though perhaps the Duck Typing wikipedia article is a better introduction. Skip bits you don't understand.) so that subclasses all behave differently -- but in a manner that "fits" with the names you give them.
Incidentally, if this were my problem to solve, I probably wouldn't have subclassed ClothingItem
for every type of clothing in the store -- that means you need to edit code in order to carry a new product. This design is good enough for learning how to work with subclassing, but this isn't an ideal use. (Instead, I'd just store the clothing type as a member of the Clothing
class. Pants, shirts, shoes, gorillas, you treat them all the same -- a name, how many you have, how much you sell them for, how much you pay for them from your supplier, etc.)
Upvotes: 3