我们在编程的过程中,并非都是要重头开始。比如其他人已经有现成的类,我们可以使用其他找人编写的类。术语称之为: 继承。

当一个类继承例外一个类时,它可以获得这个类的所有属性和方法:原有的类称之为 父类,新的类称之为子类。子类可以继承父类的所有方法和属性,还可以自定一些自己的方法和属性。

比如我们已经有了一个叫汽车的父类,我们可以继承这个类,生成一个电动车的子类:

#-*- coding:utf-8 -*-class Car():def __init__(self, make, model, year):self.make = makeself.model = modelself.year = yearself.odometer_reading = 0def get_description_name(self):long_name = str(self.year) + ' ' + self.make + ' ' + self.modelreturn 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 = mileageelse:print("You cannot do that.")def increase_odometer(self, miles):if miles >= 0:self.odometer_reading += mileselse: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的子类。

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

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

通过上面的例子,我们可以看到,子类可以正确的调用父类的方法,实际上这时已经是子类的方法了。

我们也可以根据累的特性,给子类定义自己特有的属性和方法:

比如电动车有一个电瓶,并且有方法可以实时的显示当前的电量。

#-*- coding:utf-8 -*-class Car():def __init__(self, make, model, year):self.make = makeself.model = modelself.year = yearself.odometer_reading = 0def get_description_name(self):long_name = str(self.year) + ' ' + self.make + ' ' + self.modelreturn 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 = mileageelse:print("You cannot do that.")def increase_odometer(self, miles):if miles >= 0:self.odometer_reading += mileselse: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 = 100def 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__方法中,添加了一个电瓶容量的属性,

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 = makeself.model = modelself.year = yearself.odometer_reading = 0def get_description_name(self):long_name = str(self.year) + ' ' + self.make + ' ' + self.modelreturn 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 = mileageelse:print("You cannot do that.")def increase_odometer(self, miles):if miles >= 0:self.odometer_reading += mileselse: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 = 100def 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 = makeself.model = modelself.year = yearself.odometer_reading = 0def get_description_name(self):long_name = str(self.year) + ' ' + self.make + ' ' + self.modelreturn 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 = mileageelse:print("You cannot do that.")def increase_odometer(self, miles):if miles >= 0:self.odometer_reading += mileselse: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 = sizedef 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 = makeself.model = modelself.year = yearself.odometer_reading = 0def get_description_name(self):long_name = str(self.year) + ' ' + self.make + ' ' + self.modelreturn 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 = mileageelse:print("You cannot do that.")def increase_odometer(self, miles):if miles >= 0:self.odometer_reading += mileselse: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 = sizedef 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
'''

转载于:https://www.cnblogs.com/wanghao4023030/p/10896836.html

Python 学习笔记13 类 - 继承相关推荐

  1. Python学习笔记 (类与对象)

    Python学习笔记 (类与对象) 1.类与对象 面向对象编程语言类: 一个模板, (人类)-是一个抽象的, 没有实体的对象: (eg: 张三, 李四) 属性: (表示这类东西的特征, 眼睛, 嘴巴, ...

  2. python面向对象编程72讲_2020-07-22 Python学习笔记27类和面向对象编程

    一些关于自己学习Python的经历的内容,遇到的问题和思考等,方便以后查询和复习. 声明:本人学习是在扇贝编程通过网络学习的,相关的知识.案例来源于扇贝编程.如果使用请说明来源. 第27关 类与面向对 ...

  3. Python学习笔记(13)-Python类与对象示例

    点此查看 零基础Python全栈文章目录及源码下载 本文目录 1. 简介 2. Python类的定义 3. Python类的动态语言特性 4. Python类中属性的访问控制 1. 简介 Python ...

  4. Python学习笔记:类

    本文来自:入门指南 开胃菜参考:开胃菜 使用Python解释器:使用Python解释器 本文对Python的简介:Python 简介 Python流程介绍:深入Python 流程 Python数据结构 ...

  5. python学习笔记(类)

    类中一个常见的魔术方法 class pipei():def __init__(self,name,age,high): self.name = nameself.age = ageself.high ...

  6. python学习笔记(面向对象,类)

    一.类的定义 1.类的基本结构 #命名规则: 驼峰法 class Student(): # 使用class 定义类a= 1 # 变量name = '小明'def aa(self): # 函数print ...

  7. python学习笔记:类的方法总结

    python中类的方法总结 在python中,类的方法有如下三种: (1)实例方法(即:对象方法) (2)类方法 (3)静态方法 下面,将对这三种方法进行总结. 1.实例方法(对象方法) 通常情况下, ...

  8. Python 学习笔记12 类 - 使用类和实例

    当我们熟悉和掌握了怎么样创建类和实例以后,我们编程中的大多数工作都讲关注在类的简历和实例对象使用,修改和维护上. 结合实例我们来进一步的学习类和实例的使用: 我们新建一个汽车的类: #-*- codi ...

  9. Python学习笔记28:从协议到抽象基类

    Python学习笔记28:从协议到抽象基类 今后本系列笔记的示例代码都将存放在Github项目:https://github.com/icexmoon/python-learning-notes 在P ...

最新文章

  1. sklearn使用pipeline、ParameterGrid以及GridSearchCV进行超参数调优
  2. python流程控制-实战案例手把手教你Python流程控制技巧
  3. C++ Primer 5th笔记(chap 17 标准库特殊设施)随机数
  4. 网信号好怎么不显示无服务器,苹果iPhone12经常出现无服务状态 信号不好怎么解决...
  5. Java——容器(泛型)
  6. mysql 变量生命周期_Go: 延长变量的生命周期
  7. 适用于WordPress网站的12个最佳计算器插件
  8. 企业微信邮箱登录入口在哪里?
  9. 智慧城市解决方案(智慧城市系统及相关技术)
  10. 几种不同的json格式解析
  11. QT txt读写—论坛体编辑器
  12. ★Kali信息收集~ 5.The Harvester:邮箱挖掘器
  13. ERP发货系统的修改(四十三)
  14. 工作记录 --01 验证证件号合法性!
  15. js 把数字转换成万
  16. 安利三个工具,教你如何把英语翻译成中文
  17. Linux如何管理进程
  18. druid.io剖析
  19. 正则看这三个网站就够了
  20. 编写函数求两个数的最大公约数,采用递归法计算两数的最大公约数。

热门文章

  1. [CareerCup] 17.7 English Phrase Describe Integer 英文单词表示数字
  2. 使用克隆配置任务配置边缘传输服务器角色
  3. [bzoj 2434][Noi2011]阿狸的打字机
  4. httpWebRequest 错误
  5. DataGrid能否动态合并一笔订单下面的多个交易
  6. .net 2.0 BackgroundWorker类详细用法
  7. “艾妮”(ANI)蠕虫病毒
  8. Swift和Javascript的神奇魔法
  9. 4月全球操作系统市场份额:Win 7份额连续4月上涨
  10. Delphi与Ole,Word,Excel,查找与替换等