举例讲解Python面向对象编程中类的继承
2019/7/13 23:30:10
本文主要是介绍举例讲解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面向对象编程中类的继承的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python