简体   繁体   English

在父子 Class 中使用 If 条件 Python

[英]Using If conditions in Parent/child Class in Python

#I have a parent class vehicle and two child class: Bus and Cars. #I have a parent class vehicle and two child class:公共汽车和汽车。 I am trying to put a condition where if Vehicle is Bus, it should return white color while if class in Cars, it should return Red, NOTE: I don't wan specify default color under child class我正在尝试设置一个条件,如果 Vehicle 是 Bus,它应该返回白色,而如果是 Cars 中的 class,它应该返回红色,注意:我不想在 child class 下指定默认颜色

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

    def color(self):
        if Vehicle == Cars:
            return "Red"
        else:
            return "White"


class Bus(Vehicle):
    pass

class Cars(Vehicle):
    pass


School_bus = Bus("School Volvo", 12)
Racing_Car1 = Cars("Audi", 10)
Racing_Car2 = Cars("BMW", 5)


print("The Bus has Color:", School_bus.color())
print("The car has color:", Racing_Car2.color())

Check whether the argument is a Cars with isinstance() , and if not, test if it has a color attribute with hasattr() :使用isinstance()检查参数是否是Cars ,如果不是,则使用hasattr()测试它是否具有color属性:

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>"

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.它在创建 Object 时设置颜色。您以后不需要检查它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM