zoukankan      html  css  js  c++  java
  • 015: class and objects > 多重继承

    1. 简单多重继承:

    多重继承一个比较麻烦的问题就是父类的初始化的问题,下面这个例子算是一般比较常见的方式。但是这种方式存在着一个问题,那就是object的初始化函数将运行两次,一般情况下这不会产生什么问题,但是有时候可能会引起设计上的致命缺陷。

    class Mother(object):
        def __init__(self, first_name):
            self.first_name = first_name
    
    class Father(object):
        def __init__(self, last_name):
            self.last_name = last_name
    
    class Child(Mother, Father):
        def __init__(self, first_name, last_name):
            Mother.__init__(self, first_name)
            Father.__init__(self, last_name)
    
    Tom = Child('Tom', 'Jim')    
    
    print(Tom.first_name, Tom.last_name)

     下面的例子体现了父类初始化两次的例子,一般情况下,这并不是太常见。

    class BaseClass(object):
        def __init__(self, age):
            self.age = age
            print("BaseClass' __init__ is invoked.")
    
    class Mother(BaseClass):
        def __init__(self, first_name, age):
            BaseClass.__init__(self, age)
            self.first_name = first_name
    
    class Father(BaseClass):
        def __init__(self, last_name, age):
            BaseClass.__init__(self, age)
            self.last_name = last_name
    
    class Child(Mother, Father):
        def __init__(self, first_name, last_name, age):
            Mother.__init__(self, first_name, age)
            Father.__init__(self, last_name, age)
    
    Tom = Child('Tom', 'Yao', 12)    
    
    print(Tom.first_name, Tom.last_name)

    2. 使用字典参数来实现,爷爷类只被调用一次

    class BaseClass(object):
        def __init__(self, age = '', **kwargs):
            self.age = age
            print("BaseClass' __init__ is invoked.")
    
    class Mother(BaseClass):
        def __init__(self, first_name = '', **kwargs):
            super().__init__(**kwargs)
            self.first_name = first_name
    
    class Father(BaseClass):
        def __init__(self, last_name = '', **kwargs):
            super().__init__(**kwargs)
            self.last_name = last_name
    
    class Child(Mother, Father):
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
    
    Tom = Child(**{"age":21, "first_name":"Miles", "last_name":"Yao"})    
    
    print(Tom.first_name, Tom.last_name)
  • 相关阅读:
    zhcon安装过程记录
    diff和patch配合使用(转载备用)
    Linux /etc/passwd 和 /etc/group 文件格式
    APT 常用功能
    Linux邮件服务器架构
    出现segment fault 错误的几种原因
    位运算
    Linux启动过程中几个重要配置文件的执行过程
    2016-2017 ACM-ICPC, South Pacific Regional Contest (SPPC 16)
    Codeforces Round #439 (Div. 2) 题解
  • 原文地址:https://www.cnblogs.com/jcsz/p/5140680.html
Copyright © 2011-2022 走看看