举例讲解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读取txt文件数据的方法(用于接口自动化参数化数据)

Python读取txt文件数据的方法(用于接口自动化参数化数据)

小试牛刀: 1.需要python如何读取文件 2.需要python操作list 3.需要使用split()对字符串进行分割 代码运行截图 : 代码(copy) #encoding=...

python代码 if not x: 和 if x is not None: 和 if not x is None:使用介绍

代码中经常会有变量是否为None的判断,有三种主要的写法: 第一种是`if x is None`; 第二种是 `if not x:`; 第三种是`if not x is None`(这句...

浅谈Python的条件判断语句if/else语句

计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。 比如,输入用户的年龄,根据年龄打印不同的内容。。。 Python程序中,能让计算机自己作出判断的语句就是if语句: 例:...

Python设计模式之代理模式实例

翻墙常用的方式就是使用代理(Proxy),其基本过程如下: 浏览器<-->代理服务器<-->服务器 如果浏览器请求不到服务器,或者服务器无法响应浏览器,我们可以设...

详解python的sorted函数对字典按key排序和按value排序

详解python的sorted函数对字典按key排序和按value排序

1.sorted函数按key值对字典排序 先来基本介绍一下sorted函数,sorted(iterable,key,reverse),sorted一共有iterable,key,reve...