举例讲解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实现求最长回文子串长度

给定一个字符串,求它最长的回文子串长度,例如输入字符串'35534321',它的最长回文子串是'3553',所以返回4。 最容易想到的办法是枚举出所有的子串,然后一一判断是否为回文串,返...

python列表操作使用示例分享

复制代码 代码如下:Python 3.3.4 (v3.3.4:7ff62415e426, Feb 10 2014, 18:13:51) [MSC v.1600 64 bit (AMD64...

详解Python中内置的NotImplemented类型的用法

它是什么?   >>> type(NotImplemented) <type 'NotImplementedType'> NotImpl...

Python编写带选项的命令行程序方法

运行python程序时,有时需要在命令行传入一些参数。常见的方式是在执行时,在脚本名后直接追加空格分隔的参数列表(例如 python test.py arg0 arg1 arg2),然后...

Python内置函数 next的具体使用方法

Python 3中的File对象不支持next()方法。 Python 3有一个内置函数next(),它通过调用其next ()方法从迭代器中检索下一个项目。 如果给定了默认值,则在迭代...