supper 最基本的使用方法:
重写父类的构造方法 再调用父类的构造方法
能够调用父类的构造方法,再调用父类的构造方法
python">class A(object):
def __init__(self):
print('A')
class B(A):
def __init__(self):
super().__init__() #super() 函数,不能不加括号!
print('----B----')
b = B()
基本应用方式
输出结果:
A
----B----
继承了父类的方法,再重写父类的方法
如果继承的类中在初始化时需要输入其他变量,此时的继承就需要这样做:
python">class RS485(Ethernet):
def __init__(self,parameter):
super().__init__(parameterDict=parameter)
python">class Ethernet(object):
def __init__(self,parameterDict):
self.com = parameterDict['EthName']
self.ip = parameterDict['ip']
self.port = parameterDict['port']
self.client = socket.socket(family=socket.AF_INET,type=socket.SOCK_STREAM)
self.socketInit()
def run1(self):
print('run')
def socketInit(self):
print(self.ip,self.port)
self.client.connect((self.ip,self.port))
class RS485(Ethernet):
def __init__(self,parameter):
super().__init__(parameterDict=parameter)
print(self.ip)
print(self.port)
def printserial(self):
print(self.ip)
print(self.port)
def getParameterDict(file,type,port):
with open(file,'r',encoding='utf-8') as f:
objectDict = json.load(f)
for key in objectDict:
if key == type:
portList = objectDict[key]
for portDict in portList:
for portDictKey in portDict:
if portDict[portDictKey] == port:
portParameterDict = portDict
return portParameterDict
eth0Parameter = getParameterDict('GWConfig.txt','ETH','eth0')
# eth1 = Ethernet(eth0Parameter)
# eth1.recvJsonString()
parameter = getParameterDict('GWConfig.txt','ETH','eth0')
serial1 = RS485(parameter)
serial1.run1()
这样就实现了继承,通过super的方式超继承。
以上的调用方式为示例,其实更多的方式则是继承父类的属性值
super()._init(name,age,weight),通过这样的方式继承父类的这些属性,但是这属于软编码的方式,也就是父类的名字可以随便更改的方式,但是并不影响子类的集成,子类继承一次Person即可,如果Person变成了People也是没问题的,只要修改继承的类即可
但是如果采用硬编码的方式:
Person._init(self,name,age,weight) 此时,如果父类变成了People,那么这里也需要改成People
结合继承和 object._mro()的例子:
python">class A(object):
def __init__(self):
print("A")
class C(A):
def __init__(self):
print("C")
super().__init__()
class B(A):
def __init__(self):
print("B")
super().__init__()
class D(B,C):
def __init__(self):
print("D")
super().__init__()
if __name__ == '__main__':
d = D()
print(D.__mro__)
运行结果:
D
B
C
A
(<class ‘main.D’>, <class ‘main.B’>, <class ‘main.C’>, <class ‘main.A’>, <class ‘object’>)
从中可以查看到继承顺序