1

I am creating a search function that loops through a list of variables based on different subclasses. As they have some individual attributes, I need a way to separate them through a conditional.

I have already tried using the type(x) function, which do indicate something in the right direction - But I cant seem to figure out how to use it in the conditional.

class Vehicle:
    def __init__ (self, colour="", wheels=0)
    self.colour = colour
    self.wheels = wheels

class Car(Vehicle):
    def __init__ (self, colour="", wheels=0, roof="")
        super().__init__(colour, wheels)
        self.roof = roof

class Motorcycle(Vehicle):
    def __init__ (self, colour="", wheels=0, bags="")
        super().__init__(colour, wheels)
        self.bags = bags

a = Car("red", 4, "glass")
b = Car("green", 4, "cabriolet")
c = Motorcycle("yellow", 2, "saddle")
d = Motorcycle("red", 2, "rear")

list = [a, b, c, d]
search = "saddle" 

for item in list:
    if type(item) == 'Car':                  <-- The key part
        if re.search(search, item.roof):       
        print('Found')
    elif type(item) == 'Motorcycle':         <-- The key part
        if re.search(search, item.bags):       
        print('Found')
  • 1
    Did you try `isinstance(item, Car)`? – vezunchik Mar 23 '19 at 20:37
  • This isn't javascript... `type(x)` returns the actual class, not the name of the class. – Aran-Fey Mar 23 '19 at 20:38
  • 3
    You should really make this more *object oriented* and give each class something like a `def contains(self, search_str)`, and let it figure out on its own whether it matches. Then you don’t need to figure out what class it is at all. – deceze Mar 23 '19 at 20:39

0 Answers0