2018年11月17日 星期六

[ Python 常見問題 ] python multiple inheritance passing arguments to constructors using super

Source From Here 
Question 
Consider the following snippet of python code: 
  1. class A(object):  
  2.     def __init__(self, a):  
  3.         self.a = a  
  4.   
  5. class B(A):  
  6.     def __init__(self, a, b):  
  7.         super(B, self).__init__(a)  
  8.         self.b = b  
  9.   
  10. class C(A):  
  11.     def __init__(self, a, c):  
  12.         super(C, self).__init__(a)  
  13.         self.c = c  
  14.   
  15. class D(B, C):  
  16.     def __init__(self, a, b, c, d):  
  17.         #super(D,self).__init__(a, b, c) ???  
  18.         self.d = d  
I am wondering how can I pass ab and c to corresponding base classes' constructors

How-To 
Well, when dealing with multiple inheritance in general, your base classes (unfortunatelyshould be designed for multiple inheritance. Classes B and C in your example aren't, and thus you couldn't find a proper way to apply super in D

One of the common ways of designing your base classes for multiple inheritance, is for the middle-level base classes to accept extra args in their __init__ method, which they are not intending to use, and pass them along to their super call. 

Here's one way to do it in python: 
  1. class A(object):  
  2.     def __init__(self, a):  
  3.         self.a = a  
  4.           
  5.     def showA(self):  
  6.         print("A.a={}".format(self.a))  
  7.       
  8. class B(A):  
  9.     def __init__(self, b, **kw):  
  10.         self.b=b  
  11.         super(B, self).__init__(**kw)  
  12.           
  13.     def showB(self):  
  14.         print("B.b={}".format(self.b))  
  15.           
  16. class C(A):  
  17.     def __init__(self, c, **kw):  
  18.         self.c=c  
  19.         super(C, self).__init__(**kw)  
  20.           
  21.     def showC(self):  
  22.         print("C.c={}".format(self.c))  
  23.           
  24. class D(B,C):  
  25.     def __init__(self, a, b, c, d):  
  26.         super(D, self).__init__(a=a, b=b, c=c)  
  27.         self.d = d  
  28.           
  29.     def showD(self):  
  30.         print("D.d={}".format(self.d))  
  31.           
  32. d = D(a='a', b='b', c='c', d='d')  
  33. d.showA()  
  34. d.showB()  
  35. d.showC()  
  36. d.showD()  
The execution result: 
A.a=a
B.b=b
C.c=c
D.d=d

Supplement 
Tutorialspoint - Python 3 - Object Oriented

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...