1.使用未绑定方法逐个调用
2.使用super()函数。注意,这里有个特别要注意的地方,当子类继承于多个父类时,super() 函数只可用于调用第一个父类的构造函数,其余父类的构造函数只能使用未绑定的方式调用。
直接看代码吧!!
class Employee:
def __init__(self, salary):
self.salary = salary
def work(self, *args, **kwargs):
print('普通员工在写代码,工资为:', self.salary)
class Customer:
def __init__(self, favourite, address):
self.favourite = favourite
self.address = address
def info(self):
print('我是一个顾客,我的爱好是:%s,地址是%s' % (self.favourite, self.address))
class Mannager(Employee, Customer):
def __init__(self, salary, favourite, address):
print('Manngaer的构造方法')
# 方法一:用未绑定方法来构造,使用类名直接构造,逐个调用
# Employee.__init__(self,salary)
# Customer.__init__(self,favourite,address)
# 方法二:使用super()和未绑定方法
super().__init__(salary)
# 与上一行代码效果相同
# super(Mannager,self).__init__(salary)
Customer.__init__(self, favourite, address)
m = Mannager(25000, 'it产品', '广州')
m.work()
m.info()
下面的可以不用看,没啥用!(我做笔记用的上面,就可以解决你的问题!!)
python2和python3使用super()区别
python3.x 和 python2.x 的一个区别是:
python3 可以使用直接使用 super().xxx代替 super(Class, self).xxx 。
class A:
def add(self, x):
y = x+1
print(y)
class B(A):
def add(self, x):
super().add(x) # python2.x:super(B, self).add(x)
b = B()
b.add(2) # 3
super()单类继承
在单类继承中,其意义就是不需要父类的名称来调用父类的函数,因此当子类改为继承其他父类的时候,不需要对子类内部的父类调用函数做任何修改就能调用新父类的方法。
# 定义父类base1 # 定义父类base2
class base1(object): # class base2(object):
def __init__(self): # def __init__(self):
print("base1 class") # print("base2 class")
# 不使用super(),若继承父类base2,需要修改内部的父类调用函数,都换成base2
class A(base1): # class A(base2):
def __init__(self): # def __init__(self):
base1.__init__(self) # base2.__init__(self)
# 使用super(),只需要修改类的定义,第一行
class B(base1): # class B(base2):
def __init__(self): # def __init__(self):
super(B, self).__init__() # super(B, self).__init__()
这里要注意的是
base1.__init__(self)vs.super(B, self).__init__(),后者:由于super将传入self作为调用__init__默认的第一个变量,因此在声明的时候不需要显式表示self。
此外由于super返回的是代理对象,因此父类只能调用一次,也就避免了如下异常的可能性。
base1 = A
base1() # 无限递归
1
2
super()多类继承
在多类继承中super()是必不可少的(多类继承是python的一大特色)。
super()的__mro__变量记录了方法解析搜索顺序,即一个类的所有父类的调用顺序(MRO用来保证多类继承的时候各父类被逐一调用并只被调用一次)。
# -*- coding: UTF-8 -*-
# 定义父类base1
class base1(object):
def __init__(self):
pass
# 定义子类B继承父类base1
class B(base1):
def __init__(self):
super(B, self).__init__()
# 定义子类mixin继承父类base1
class mixin(base1):
def __init__(self):
super(mixin, self).__init__()
class C(B, mixin): # 1. mixin类插入到了B类和base1类之间
pass
if __name__ == '__main__':
C()
print(C.__mro__) # 2. 方法解析顺序(MRO): C -> B -> mixin -> base1