# 零基础学Python继承——子承父类

XAMPP案例 457浏览

1

``````class Bike:
``````    def __init__(self,model,year):
``````        self.model = model
``````        self.year = year
``````        self.distance = 0
``````    def dis(self):
``````        print(f'The {self.model} has {self.distance} km on it.')
``````    def update_dis(self,km):
``````        if km >= self.distance:
``````            self.distance = km
``````        else:
``````            print("Wrong behavior!")
``````
``````class Mountain_bike(Bike):
``````    def __init__(self,model,year):
````        super().__init__(model,year)````

``````new_bike = Mountain_bike('XC',2021)
````new_bike.dis()````

``The XC has 0 km on it.``

2

``````class Mountain_bike(Bike):
``````    def __init__(self,model,year):
``````        super().__init__(model,year)
``````        self.transmission = 27
``````    def speed_changer(self):
````        print(f"The {self.model} has {self.transmission} shifting.")````

``````new_bike = Mountain_bike('XC',2021)
``````new_bike.speed_changer()
````The XC has 27 shifting.````

3

``````class Mountain_bike(Bike):
``````    def __init__(self,model,year):
``````        super().__init__(model,year)
``````        self.transmission = 27
``````    def speed_changer(self):
``````        print(f"The {self.model} has {self.transmission} shifting.")
``````    def update_dis(self): #和父类方法同名
````        print('You can not do this!')````

``````new_bike = Mountain_bike('XC',2021)
``````new_bike.update_dis()
````You can not do this!````

4

``````class Transmission:
``````    def __init__(self,transmission = 27):
``````        self.transmission = transmission
``````    def speed_changer(self):
````        print(f"The bike has {self.transmission} shifting.")````

``````class Mountain_bike(Bike):
``````    def __init__(self,model,year):
``````        super().__init__(model,year)
````        self.trans = Transmission() #实例用作属性````

``````new_bike = Mountain_bike('XC',2021)
````new_bike.trans.speed_changer()````

``The bike has 27 shifting.``