举例讲解Python面向对象编程中类的继承

yipeiwu_com6年前Python基础

python创建一个类很简单只需要定义它就可以了.

class Cat:
  pass

就像这样就可以了,通过创建子类我们可以继承他的父类(超类)的方法。这里重新写一下cat

class Cat:
  name = 'cat'


class A(Cat):
  pass

print A.name  # cat

经典类

我们也可以这样,让A多继承。

class Cat:
  name = 'cat'


class Dog:
  name = 'dog'


class A(Cat, Dog):
  pass

print A.name  # cat

如果Cat类没有name属性呢?

class Cat:
  pass

  ...
print A.name  # dog

A就会在其他的父类中找name这个属性。如果继承的两个父类都是继承自Animal类而Animal类也有name属性呢?

class Animal:
  name = 'animal'


class Cat(Animal):
  pass


class Dog(Animal):
  name = 'dog'


class A(Cat, Dog):
  pass

print A.name  # animal

这样A就不会在Dog类中找而是会在Animal上找到name, 这种类叫经典类。类的解析顺序是一种从左到右深度优先的搜索。也就是A–> Cat–> Animal –> Dog。

新式类

python还有一种创建类的方式,就是使用新式类(建议使用), 都继承自object这个基类, 新式类的搜索规则是从左到右逐级查询。也就是A–> Cat –> Dog –> Animal。

class Cat(object):
  pass

相关文章

python持久性管理pickle模块详细介绍

持久性就是指保持对象,甚至在多次执行同一程序之间也保持对象。通过本文,您会对 Python对象的各种持久性机制(从关系数据库到 Python 的 pickle以及其它机制)有一个总体认识...

Pandas数据离散化原理及实例解析

Pandas数据离散化原理及实例解析

这篇文章主要介绍了Pandas数据离散化原理及实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 为什么要离散化 连续属性离...

解决tensorflow测试模型时NotFoundError错误的问题

错误代码如下: NotFoundError (see above for traceback): Unsuccessful TensorSliceReader constructor...

python itchat给指定联系人发消息的方法

itchat模块 官方参考文档:https://itchat.readthedocs.io/zh/latest/ 安装 pip install itchat / pip3 insta...

Python利用Django如何写restful api接口详解

Python利用Django如何写restful api接口详解

前言 用Python如何写一个接口呢,首先得要有数据,可以用我们在网站上爬的数据,在上一篇文章中写了如何用Python爬虫,有兴趣的可以看看:/post/141661.htm 大量的数...