• python3下的super()


    大家都知道super是用来解决python钻石多重继承出现的基类重复调用的问题,这个就不赘述了,不了解的请点击

    但是我发现还有个问题在于不是钻石继承时继承先后顺序的问题,也就是如果mixin与继承的某子类同时作为某类的父类时,其书写顺序对于super可能产生的不同影响:

    假设有个情景是是打印租房信息,有一套房子中的一间婴儿房准备出租:

     1 class room:
     2     def __init__(self,area=120,usedfor='sleep'):
     3         self.area = area
     4         self.usedfor = usedfor
     5 
     6     def display(self):
     7         print("this is my house")
     8 
     9 class babyroom(room):
    10     def __init__(self,area=40,usedfor="son",wallcolor='green'):
    11         super().__init__(area,usedfor)
    12         self.wallcolr = wallcolor
    13 
    14     def display(self):
    15         super().display()
    16         print("babyroom area:%s wallcollor:%s"%(self.area,self.wallcolr))
    17 
    18 class rent:
    19     def __init__(self,money=1000):
    20         self.rentmoney = money
    21 
    22     def display(self):
    23         print("for rent at the price of %s"%self.rentmoney)
    24 
    25 class agent(babyroom,rent):
    26 # class agent(rent,babyroom):
    27     def display(self):
    28         super().display()
    29         print("rent house agent")
    30 
    31 agent().display()
    32 
    33 在理想中我们希望所有类的都能够输出,也就是:
    34 this is my house
    35 babyroom area:40 wallcollor:green
    36 for rent at the price of 1000
    37 rent house agent
    38 
    39 但是实际输出并不是这样的,看到上面两种写法:
    40 写法1的输出:
    41 this is my house
    42 babyroom area:40 wallcollor:green
    43 rent house agent
    44 也就是说并没有调用rent类的display方法
    45 
    46 写法二的输出:
    47 for rent at the price of 1000
    48 rent house agent
    49 也就是说babyroom以及room类的display方法都没有调用

    需要补充的是两种写法中查看agent.__mro__会发现所有类都在,并没有缺失。

    所以我认为在此存在传递中断的问题,当两个父类并不是兄弟类时,遇到super()并不会相互传递,二是直接选择走第一个的那条路线!!

    这就提醒我们在mixin入的类里尽量不要使用和其他存在继承关系的类相同的方法名,即使都是表达的是打印信息到屏幕的方法

  • 相关阅读:
    Docker镜像和容器
    Docker介绍
    Ansible实战:部署分布式日志系统
    Ansible之roles介绍
    Ansible之tags介绍
    Ansible之迭代、模板
    linux jenkins安装(四)
    linux maven安装(三)
    linux tomcat安装(二)
    linux JDK安装(一)
  • 原文地址:https://www.cnblogs.com/pengsixiong/p/5449546.html
Copyright © 2020-2023  润新知