举例讲解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控制键盘鼠标pynput的详细用法

pynput这个库让你可以控制和监控输入设备。 对于每一种输入设备,它包含一个子包来控制和监控该种输入设备: pynput.mouse:包含控制和监控鼠标或者触摸板的类。 py...

Python文件读写常见用法总结

1. 读取文件 # !/usr/bin/env python # -*- coding:utf-8 -*- """ 文件读取三步骤: 1.打开文件 f=open(file...

用Python操作字符串之rindex()方法的使用

 rindex()方法返回所在的子str被找到的最后一个索引,可选择限制搜索的字符串string[beg:end] 如果没有这样的索引存在,抛出一个异常。 语法 以下是rind...

详解Python中的Numpy、SciPy、MatPlotLib安装与配置

详解Python中的Numpy、SciPy、MatPlotLib安装与配置

用Python来编写机器学习方面的代码是相当简单的,因为Python下有很多关于机器学习的库。其中下面三个库numpy,scipy,matplotlib,scikit-learn是常用组...

pygame游戏之旅 添加游戏暂停功能

pygame游戏之旅 添加游戏暂停功能

本文为大家分享了pygame游戏之旅的第13篇,供大家参考,具体内容如下 定义暂停函数: def paused(): largeText = pygame.font.SysFont...