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)