Python 学习笔记13 类 - 继承

咱们在编程的过程当中,并不是都是要重头开始。好比其余人已经有现成的类,咱们可使用其余找人编写的类。术语称之为: 继承。编程

当一个类继承例外一个类时,它能够得到这个类的全部属性和方法:原有的类称之为 父类,新的类称之为子类。子类能够继承父类的全部方法和属性,还能够自定一些本身的方法和属性。dom

好比咱们已经有了一个叫汽车的父类,咱们能够继承这个类,生成一个电动车的子类:spa

#-*- coding:utf-8 -*-

class Car():

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_description_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()

    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You cannot do that.")

    def increase_odometer(self, miles):
        if miles >= 0:
            self.odometer_reading += miles
        else:
            print("The value is invalid, please input the number which should more than zero.")

'''继承car,生成一个新类'''
class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)



my_BYD = ElectricCar("BYD", "Tang", 2019)
print(my_BYD.get_description_name())


'''
输出:
2019 Byd Tang
'''

 

经过上面的代码,咱们看到,咱们基于一个car的父类,生成了一个ElectricCar的子类。code

在类定义是,在括号里面包含父类的名称,来表示继承这个类: class NewClass(SupperClass)。对象

而真正继承父类的方法和属性的,则是在__init__方法中的super()方法的使用,该方法告诉Python使用父类的__init__方法,来从新构造一个类。blog

经过上面的例子,咱们能够看到,子类能够正确的调用父类的方法,实际上这时已是子类的方法了。继承

咱们也能够根据累的特性,给子类定义本身特有的属性和方法:ip

好比电动车有一个电瓶,而且有方法能够实时的显示当前的电量。utf-8

#-*- coding:utf-8 -*-

class Car():

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_description_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()

    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You cannot do that.")

    def increase_odometer(self, miles):
        if miles >= 0:
            self.odometer_reading += miles
        else:
            print("The value is invalid, please input the number which should more than zero.")

'''继承car,生成一个新类'''
class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        self.battery_size = 100

    def describe_battery(self):
        print("Catr has " + str(self.battery_size) + "-kwh battery. " )



my_BYD = ElectricCar("BYD", "Tang", 2019)
print(my_BYD.get_description_name())
my_BYD.describe_battery()


'''
输出:
2019 Byd Tang
Catr has 100-kwh battery. 
'''

 

在上述代码中,咱们能够看到,咱们在__init__方法中,添加了一个电瓶容量的属性,get

self.battery_size = 100

 

而且添加了一个电动车特有的显示电量的方法。

    def describe_battery(self):
        print("Catr has " + str(self.battery_size) + "-kwh battery. " )

这些方法是属于子类(ElectricCar)的,它可以正确的被运行。

当父类中的某些方法,并不适用子类的时候怎么办呐?咱们能够在子类中从新定义该方法。

好比Car类中有加汽油的方法,而这对电动车并不适用,咱们能够在子类中对这个方法进行覆盖重写。子类在调用这个方法时,将采用子类的定义:

#-*- coding:utf-8 -*-

class Car():

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_description_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()

    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You cannot do that.")

    def increase_odometer(self, miles):
        if miles >= 0:
            self.odometer_reading += miles
        else:
            print("The value is invalid, please input the number which should more than zero.")

    def fill_gas(self):
        print("Car is filling gas.")

'''继承car,生成一个新类'''
class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        self.battery_size = 100

    def describe_battery(self):
        print("Catr has " + str(self.battery_size) + "-kwh battery. " )

    def fill_gas(self):
        print("Electric car no gas tank.")



my_BYD = ElectricCar("BYD", "Tang", 2019)
my_BYD.fill_gas()


'''
输出:
Electric car no gas tank.
'''

 

咱们在编写代码时候,须要灵活的对类进行定义。在编程思想中,现实生活中的全部对象,均可以被定义成类。

咱们尽量多订一些类,以简化咱们的代码长度,同时也变成程序代码的维护和修改。

好比在上述例子中,咱们对电动车类增长了一个电池的属性和相关的方法。其实咱们也能够新建一个电池的类,将电池特有的属性和方法独立开来。这样咱们能够根据这个类生成各式各样的实例:

#-*- coding:utf-8 -*-

class Car():

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_description_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()

    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You cannot do that.")

    def increase_odometer(self, miles):
        if miles >= 0:
            self.odometer_reading += miles
        else:
            print("The value is invalid, please input the number which should more than zero.")

    def fill_gas(self):
        print("Car is filling gas.")


'''生成一个电池类'''
class Battery():
    def __init__(self, size = 100):
        self.size = size

    def describe_battery(self):
        print("Battery has " + str(self.size) + "-kwh battery. " )

'''继承car,生成一个新类'''
class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        self.battery = Battery()

    def fill_gas(self):
        print("Electric car no gas tank.")



my_BYD = ElectricCar("BYD", "Tang", 2019)
my_BYD.battery.describe_battery()


'''
输出:
Battery has 100-kwh battery. 
'''

 

我么能够看到咱们增长了一个电池类Battery(),该类有本身属性 size和方法describe_battery。咱们在定义电动车时,增长了一个battery的属性,这个属性是一个baterry的实例,咱们能够认为该属性其实是一个对象 object,咱们能够操做和使用它的属性和方法。

这样作的好处就是,有关电池的属性和方法的修改,能够放在battery类中进行处理。EelctricCar类中,只关注与其相关的属性和方法。好比咱们能够添加一个电池能跑多少里程的方法,该方法与电池的容量相关:

#-*- coding:utf-8 -*-

class Car():

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_description_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()

    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You cannot do that.")

    def increase_odometer(self, miles):
        if miles >= 0:
            self.odometer_reading += miles
        else:
            print("The value is invalid, please input the number which should more than zero.")

    def fill_gas(self):
        print("Car is filling gas.")


'''生成一个电池类'''
class Battery():
    def __init__(self, size = 100):
        self.size = size

    def describe_battery(self):
        print("Battery has " + str(self.size) + "-kwh battery. " )

    def show_range(self):
        print("Battery has " + str(self.size * 3) + " killmaters on full charge")

'''继承car,生成一个新类'''
class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        self.battery = Battery()

    def fill_gas(self):
        print("Electric car no gas tank.")



my_BYD = ElectricCar("BYD", "Tang", 2019)

my_BYD.battery.describe_battery()
my_BYD.battery.show_range()
my_BYD.battery.size = 200
my_BYD.battery.describe_battery()
my_BYD.battery.show_range()
'''
输出:
Battery has 100-kwh battery. 
Battery has 300 killmaters on full charge
Battery has 200-kwh battery. 
Battery has 600 killmaters on full charge
'''
相关文章
相关标签/搜索