python3下的super()
2016-04-30 22:00
537 查看
大家都知道super是用来解决python钻石多重继承出现的基类重复调用的问题,这个就不赘述了,不了解的请点击。
但是我发现还有个问题在于不是钻石继承时继承先后顺序的问题,也就是如果mixin与继承的某子类同时作为某类的父类时,其书写顺序对于super可能产生的不同影响:
假设有个情景是是打印租房信息,有一套房子中的一间婴儿房准备出租:
需要补充的是两种写法中查看agent.__mro__会发现所有类都在,并没有缺失。
所以我认为在此存在传递中断的问题,当两个父类并不是兄弟类时,遇到super()并不会相互传递,二是直接选择走第一个的那条路线!!
这就提醒我们在mixin入的类里尽量不要使用和其他存在继承关系的类相同的方法名,即使都是表达的是打印信息到屏幕的方法
但是我发现还有个问题在于不是钻石继承时继承先后顺序的问题,也就是如果mixin与继承的某子类同时作为某类的父类时,其书写顺序对于super可能产生的不同影响:
假设有个情景是是打印租房信息,有一套房子中的一间婴儿房准备出租:
class room: def __init__(self,area=120,usedfor='sleep'): self.area = area self.usedfor = usedfor def display(self): print("this is my house") class babyroom(room): def __init__(self,area=40,usedfor="son",wallcolor='green'): super().__init__(area,usedfor) self.wallcolr = wallcolor def display(self): super().display() print("babyroom area:%s wallcollor:%s"%(self.area,self.wallcolr)) class rent: def __init__(self,money=1000): self.rentmoney = money def display(self): print("for rent at the price of %s"%self.rentmoney) class agent(babyroom,rent): # class agent(rent,babyroom): def display(self): super().display() print("rent house agent") agent().display() 在理想中我们希望所有类的都能够输出,也就是: this is my house babyroom area:40 wallcollor:green for rent at the price of 1000 rent house agent 但是实际输出并不是这样的,看到上面两种写法: 写法1的输出: this is my house babyroom area:40 wallcollor:green rent house agent 也就是说并没有调用rent类的display方法 写法二的输出: for rent at the price of 1000 rent house agent 也就是说babyroom以及room类的display方法都没有调用
需要补充的是两种写法中查看agent.__mro__会发现所有类都在,并没有缺失。
所以我认为在此存在传递中断的问题,当两个父类并不是兄弟类时,遇到super()并不会相互传递,二是直接选择走第一个的那条路线!!
这就提醒我们在mixin入的类里尽量不要使用和其他存在继承关系的类相同的方法名,即使都是表达的是打印信息到屏幕的方法
相关文章推荐
- python猜数字小游戏
- python&&CMD
- Python控制流和函数--Python学习笔记二
- Python程序的执行原理
- IronPython调用C# DLL函数方法
- Scrapy-Splash爬取淘宝排行榜(一)
- MOOC的Python笔记(一)基本语法
- python建立pip.ini
- python数据类型之list
- python 的.join()方法
- 【Python】什么是闭包
- 【Python】高阶函数介绍
- Python break和continue
- python使用zlib实现压缩与解压字符串
- 安装mysql-python:EnvironmentError: mysql_config not found
- python基础(一)
- Python核心编程 第七章练习
- python day2:python 初识(二)
- python学习之旅之python简单命令
- python range()和xrange()