举例讲解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常用函数与用法示例

本文实例讲述了python常用函数与用法。分享给大家供大家参考,具体如下: 自定义函数实例 # 定义一个函数 def printme( str ): "打印任何传入的字符串"...

Python对列表去重的多种方法(四种方法)

无聊统计了下列表去重到底有多少种方法。下面小编给大家总结一下,具体内容详情如下; 开发中对数组、列表去重是非常常见的需求,对一个list中的id进行去重,有下面几种方法,前面两种方法不能...

django 通过url实现简单的权限控制的例子

根据用户权限设定用户可以访问哪些页面,用django实现一个简单的demo。 1.models.py 文件 class level(models.Model): l_name =...

对Python通过pypyodbc访问Access数据库的方法详解

对Python通过pypyodbc访问Access数据库的方法详解

看书上通过ODBC访问数据库的案例,想实践一下在Python 3.6.1中实现access2003数据库的链接,但是在导入odbc模块的时候出现了问题,后来查了一些资料就尝试着使用pyp...

Python 网络编程之TCP客户端/服务端功能示例【基于socket套接字】

本文实例讲述了Python 网络编程之TCP客户端/服务端功能。分享给大家供大家参考,具体如下: demo.py(TCP客户端): import socket def main():...