Home > other >  Using If conditions in Parent/child Class in Python
Using If conditions in Parent/child Class in Python

Time:02-16

# I am trying to create a if condition for just class: Cars, when my car is "BMW", I want white color and when Audi I want black color. however please note that I have "Bus" as child class with default color as blue

class Vehicle:
    
    def __init__(self, name, tyre, price):
        self.name = name
        self.tyre = tyre
        self.price = price

class Bus(Vehicle):
    color = "Blue"

class Cars(Vehicle):

School_bus = Bus("Volvo", "TVS", 1200)
Racing_Car1 = Cars("Audi", "MRF", 5000)
Racing_Car2 = Cars("BMW", "MRF", 3000)

print(School_bus.name, "and its color is:", School_bus.color)
print(Racing_Car2.name, "and its color is:", Racing_Car2.color)

CodePudding user response:

Check whether the argument is a Cars with isinstance(), and if not, test if it has a color attribute with hasattr():

def get_color(vehicle):
  if isinstance(vehicle, Cars):
    if vehicle.Name == "Audi":
      return "Black"
    return "White"

  if hasattr(vehicle, "color"):
    return vehicle.color

  return "<UNKNOWN>"

CodePudding user response:

Try this Code:

class Vehicle:
    def __init__(self, name, tyre, price, color = ""):
        self.name = name
        self.tyre = tyre
        self.price = price
        self.color = color

class Bus(Vehicle):
    def __init__(self, name, tyre, price, color = ""):
        if color == "":
            color = "Blue"
        super(Bus, self).__init__(name, tyre, price, color)

class Cars(Vehicle):
    def __init__(self, name, tyre, price, color = ""):
        if color == "":
            if name == "BMW":
                color = "White"
            if name == "Audi":
                color = "Black"
        super(Cars, self).__init__(name, tyre, price, color)

School_bus = Bus("Volvo", "TVS", 1200)
Racing_Car1 = Cars("Audi", "MRF", 5000)
Racing_Car2 = Cars("BMW", "MRF", 3000)

print(School_bus.name, "and its color is:", School_bus.color)
print(Racing_Car2.name, "and its color is:", Racing_Car2.color)

It sets the Color at the creation of an Object. You don't need to check it later.

  • Related