我正在创建一个搜索函数,该函数根据不同的子类循环遍历变量列表。由于它们具有一些单独的属性,因此我需要一种通过条件将它们分开的方法。
我已经尝试过使用type(x)函数,它确实指示了正确的方向-但是我似乎无法弄清楚如何在条件条件下使用它。
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')