1

My current class:

class Animals(object):

   def __init__(self):
       self.dogs = list()
       self.cats = list()
       # a lot of species ...

   def add_animal(self, animal, category):
       if category == 'cats':
           self.cats.append(animal)
       if category == 'dogs':
           self.dogs.append(animal)
       # a lot of ifs here ...

I would like to create a universal add_animal method, something like:

def add_animal(self, animal, category):
    self[category].append(animal)

How can I achieve it?

whip
  • 53
  • 7
  • 1
    You could use `getattr(self, category)`. I'd put the lists into a dictionary however; `self.categories = {'cats': [], 'dogs': []}`. – Martijn Pieters Sep 03 '16 at 18:41
  • This seems like a weird approach in general. Why do you have to pass two arguments, rather than e.g. `if isinstance(animal, Cat)` (where `class Cat(Animal):`)? – jonrsharpe Sep 03 '16 at 18:51
  • @jonrsharpe: I'm trying to avoid using a giant **if isinstance(..)** statement. And I have got a lot of such methods in the class, so it will be problematic to change all them after every change of the categories. – whip Sep 03 '16 at 19:14

0 Answers0