class Car: def __init__(self, brand): self.brand = brand def drive(self): print(f"{self.brand} is driving.")
car = Car("Benz") car.drive() #输出 "Benz is driving."
class Car: def __init__(self, brand): self.__brand = brand def __drive(self): print(f"{self.__brand} is driving.") def run(self): self.__drive() car = Car("Benz") car.run() #输出 "Benz is driving." car.__drive() #报错,实例无法访问私有方法
class Vehicle: def drive(self): print("Vehicle is driving.") class Car(Vehicle): def drive(self): print("Car is driving.") vehicle = Vehicle() vehicle.drive() #输出 "Vehicle is driving." car = Car() car.drive() #输出 "Car is driving."
class Vehicle: def drive(self): print("Vehicle is driving.") class Car(Vehicle): def drive(self): print("Car is driving.") class Bike(Vehicle): def drive(self): print("Bike is driving.") def drive_vehicle(vehicle): vehicle.drive() vehicle = Vehicle() car = Car() bike = Bike() drive_vehicle(vehicle) #输出 "Vehicle is driving." drive_vehicle(car) #输出 "Car is driving." drive_vehicle(bike) #输出 "Bike is driving."
class Car: @property def brand(self): return self.__brand @brand.setter def brand(self, brand): self.__brand = brand car = Car() car.brand = "Benz" print(car.brand) #输出 "Benz"
class Car: def __init__(self, brand, color): self.brand = brand self.color = color def __str__(self): return f"{self.brand}({self.color})" car = Car("Benz", "red") print(car) #输出 "Benz(red)"
标签: 算法