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

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

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

#-*- 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的子类。

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

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

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

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

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

#-*- 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__方法中,添加了一个电瓶容量的属性,

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
'''

Python 学习笔记15 类 - 继承的更多相关文章

  1. python学习笔记4_类和更抽象

    python学习笔记4_类和更抽象 一.对象 class 对象主要有三个特性,继承.封装.多态.python的核心. 1.多态.封装.继承 多态,就算不知道变量所引用的类型,还是可以操作对象,根据类型 ...

  2. Python学习笔记8-类的继承 、深度优先、广度优先

    Python 类声明 语法: class 类名: 类体 例: #--encoding:utf-8-- # class AddressBookEntity: myVersion=0.1 def __in ...

  3. Python学习笔记 - day7 - 类

    类 面向对象最重要的概念就是类(Class)和实例(Instance),比如球类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同.在Python中,定义类 ...

  4. Python学习笔记008_类_对象_继承_组合_类相关的BIF

    # 对象 = 属性 + 方法>>> # Python中的类名约定以大写字母开始>>> # tt = Turtle() 这就是创建类实例的方法,其它语言用new ,它 ...

  5. python学习笔记(七) 类和pygame实现打飞机游戏

    python中类声明如下: class Student(object): def __init__(self, name, score): self.name = name self.score = ...

  6. python学习笔记1-元类__metaclass__

    type 其实就是元类,type 是python 背后创建所有对象的元类   python 中的类的创建规则: 假设创建Foo 这个类 class Foo(Bar): def __init__(): ...

  7. Python学习笔记12—类

    典型的类和调用方法: #!/usr/bin/env Python # coding=utf-8 __metaclass__ = type #新式类 class Person: #创建类 def __i ...

  8. Python 学习笔记 - 10.类(Class) 1

    定义 Python 的 Class 比较特别,和我们习惯的静态语言类型定义有很大区别. 1. 使用一个名为 __init__ 的方法来完成初始化.2. 使用一个名为 __del__ 的方法来完成类似析 ...

  9. Python学习笔记:类

    类可以将数据与函数封装起来,用一个例子解释,先定义一个类: class athlete: def __init__(self,a_name,a_dob=None,a_times=[]): self.n ...

随机推荐

  1. windows 10 自动升级后环境变量无效

    上个礼拜放假的时候,win10提示需要升级,我当时随手就一点更新并关机...今天,在启动项目时候尴尬了: D:\project\js\iam-web\code\iam-web>npm run d ...

  2. [好好学习]在VMware中安装Oracle Enterprise Linux (v5.7) - (5/5)

  3. 使用Jmeter聚合报告生成对比图表

    背景 最近在帮别的项目组执行性能测试,使用的工具是Jmeter.接口录制和参数化前一个人已经做好了,我主要的工作就是执行脚本,撰写测试报告.事情并不复杂,可做起来却极为耗时. 首先,由于有6组账号,分 ...

  4. 361-基于6U VPX TMS320C6678+XC7K325T 的信号处理板

    基于6U VPX TMS320C6678+XC7K325T 的信号处理板 一.板卡概述 本板卡基于6U VPX结构设计无线电信号处理平台.板卡包含1片C6678芯片,1片 FPGA XC7K325T- ...

  5. 部署Tomcat服务器

    部署Tomcat服务器,具体内容如下: 1.安装部署JDK基础环境; 2.安装部署Tomcat服务器; 3.创建JSP测试页面,文件名为test.jsp,显示服务器当前时间. 然后客户机访问Web服务 ...

  6. SSM架构 (Spring 5.0.2)添加Jackson

    第一步添加jsckson的包 <dependency> <groupId>javax.annotation</groupId> <artifactId> ...

  7. linux--mongodb安装与配置

    linux下的mongodb的安装: 在mongodb的官网上下载:mongodb-linux-x86_64-rhel62-3.2.3.gz1.解压: tar -xvf mongodb-linux-x ...

  8. 02tensorflow非线性回归以及分类的简单实用,softmax介绍

    import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # 使用numpy生成200个随机点 x_data ...

  9. Task2.设立计算图并自动计算

    1.numpy和pytorch实现梯度下降法 import numpy as np # N is batch size; N, D_in, H, D_out = 64, 1000, 100, 10 # ...

  10. XML 语法

    XML 语法规则 本节的目的是想让你了解 XML 中的语法所依据的规则,避免在编写 XML 文档的时候遇到错误. XML 的语法规则很简单,且很有逻辑.这些规则很容易学习,也很容易使用. 所有的 XM ...