Python3 类继承 导入类

参考文件:《Python编程:从入门到实践》

Car类,Car.py文件

#!/usr/local/python3.6.1/bin/python3

class Car():
    """一次模拟汽车的简单尝试"""
    odometer_reading = 0
    def __init__(self, make, model, year):
        """初始化描述汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
    def get_descriptive_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 can't roll back an odometer!")
    def increment_odometer(self, miles):
        """将里程表读数增加指定的量"""
        self.odometer_reading += miles

在Car.py文件中实例化对象,如下:

my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()

运行后的效果如下:

[root@sy-pc python3.com]# ./Car.py 
2016 Audi A4
This car has 0 miles on it.

继承

子类的方法__init__()

创建子类的实例时, Python首先需要完成的任务是给父类的所有属性赋值。 为此, 子类的方法__init__() 需要父类施以援手。

#!/usr/local/python3.6.1/bin/python3

class Car():
    """一次模拟汽车的简单尝试"""
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0
    def get_descriptive_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 can't roll back an odometer!")
    def increment_odometer(self, miles):
        self.odometer_reading += miles

class ElectricCar(Car):
    """电动汽车的独特之处"""
    def __init__(self, make, model, year):
        """初始化父类的属性"""
        super().__init__(make, model, year)

my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())

运行效果:

[root@sy-pc python3.com]# ./ElectricCar.py 
2016 Tesla Model S

导入类

如单独一个Car.py文件,单独一个ElectricCar.py文件,单独一个man.py文件;在man.py文件中,ElectricCar继承了Car,实例化一个ElectricCar对象。

Car.py文件

#!/usr/local/python3.6.1/bin/python3
#①
class Car():
    """一次模拟汽车的简单尝试"""
    odometer_reading = 0
    def __init__(self, make, model, year):
        """初始化描述汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
    def get_descriptive_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 can't roll back an odometer!")
    def increment_odometer(self, miles):
        """将里程表读数增加指定的量"""
        self.odometer_reading += miles

ElectricCar.py文件

#!/usr/local/python3.6.1/bin/python3
#②
import Car

class ElectricCar(Car.Car):
    """电动汽车的独特之处"""
    #③
    def __init__(self, make, model, year):
        """初始化父类的属性"""
        #④
        super().__init__(make, model, year)

man.py文件

#!/usr/local/python3.6.1/bin/python3

#导入ElectricCar类,并重命名为e
import ElectricCar as e
#⑤
my_tesla = e.ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())

运行man.py文件的结果为:

2016 Tesla Model S

首先是Car 类的代码(见①) 。 创建子类时, 父类必须包含在当前文件中, 且位于子类前面。 在②处, 我们定义了子类ElectricCar 。 定义子类时, 必须在括号内指定父类的

名称。 方法__init__() 接受创建Car 实例所需的信息(见③) 。

④处的super() 是一个特殊函数, 帮助Python将父类和子类关联起来。 这行代码让Python调用ElectricCar 的父类的方法__init__() , 让ElectricCar 实例包含父类的所

有属性。 父类也称为超类 (superclass) , 名称super因此而得名。

为测试继承是否能够正确地发挥作用, 我们尝试创建一辆电动汽车, 但提供的信息与创建普通汽车时相同。 在⑤处, 我们创建ElectricCar 类的一个实例, 并将其存储在变

量my_tesla 中。 这行代码调用ElectricCar 类中定义的方法__init__() , 后者让Python调用父类Car 中定义的方法__init__() 。 我们提供了实参’tesla’ 、 ‘model

s’ 和2016 。

除方法__init__() 外, 电动汽车没有其他特有的属性和方法。 当前, 我们只想确认电动汽车具备普通汽车的行为

    原文作者:飞蛾逐月
    原文地址: https://blog.csdn.net/zhou16333/article/details/73381806
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞