举例讲解Python面向对象编程中类的继承,python面向对象编程
举例讲解Python面向对象编程中类的继承,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递归
- 浅析AST抽象语法树及Python代码实现,astpython
- python下调用pytesseract识别某网站验证码的实现方法,p
- 深入理解python函数递归和生成器,深入理解python递归
- 深入浅析python定时杀进程,浅析python进程
- Python的socket模块源码中的一些实现要点分析,pythonsoc
- 在Python程序和Flask框架中使用SQLAlchemy的教程,flasksqla
- Python第三方库的安装方法总结,python安装方法
- bat和python批量重命名文件的实现代码,
- python列表的常用操作方法小结,python操作方法小结
评论关闭