python多继承(钻石继承)问题和解决方法简单示例

yipeiwu_com6年前Python基础

本文实例讲述了python多继承(钻石继承)问题和解决方法。分享给大家供大家参考,具体如下:

在菱形多继承中,如果用父类.__init__()来调用父类的初始化方法,最上层会执行两次,所以遇到这种情况,python中用super.__init__()来解决这个问题。

# -*- coding:utf-8 -*-
#! python3
class Grand_father(object):
  def __init__(self):
    print('爷爷')
class Father_left(Grand_father):
  def __init__(self):
    super(Father_left,self).__init__()
    # Grand_father.__init__(self)
    print('左边爸爸')
class Father_right(Grand_father):
  def __init__(self):
    super(Father_right, self).__init__()
    # Grand_father.__init__(self)
    print('右边爸爸')
class Me(Father_right,Father_left):
  def __init__(self):
    super(Me, self).__init__()
    # Father_left.__init__(self)
    # Father_right.__init__(self)
    print('我')
def main():
  me = Me()
if __name__ == '__main__':
  main()

运行结果:

爷爷
左边爸爸
右边爸爸

如果需要调用左边爸爸,那就执行super(右边爸爸类).

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python版简单工厂模式

python版简单工厂模式

什么是简单工厂模式 工厂模式有一种非常形象的描述,建立对象的类就如一个工厂,而需要被建立的对象就是一个个产品;在工厂中加工产品,使用产品的人,不用在乎产品是如何生产出来的。从软件开发的角...

Pytorch DataLoader 变长数据处理方式

关于Pytorch中怎么自定义Dataset数据集类、怎样使用DataLoader迭代加载数据,这篇官方文档已经说得很清楚了,这里就不在赘述。 现在的问题:有的时候,特别对于NLP任务...

使用python编写udp协议的ping程序方法

服务器端 import random from socket import * serverSocket = socket(AF_INET, SOCK_DGRAM)#建立udp协...

使用Python下载Bing图片(代码)

直接上代码:复制代码 代码如下:<span style="font-family: arial,helvetica,sans-serif; font-size: 16px;">...

深入了解Python中pop和remove的使用方法

Python关于删除list中的某个元素,一般有两种方法,pop()和remove()。 remove() 函数用于移除列表中某个值的第一个匹配项。 remove()方法语法: list...