2012-03-08 97 views
0

我想知道是否可以使用父構造函數來傳遞每個子類所需的參數。因此,例如:我可以從父構造函數獲取公共參數嗎?

Class A(): 
    def __init__(a,b): 
    ...do some stuff... 

Class B(A): 
    def __init__(c,d): 
    ...do some stuff needing a and b... 

Class C(A): 
    def __init__(e,f,g): 
    ...do some stuff needing a and b... 

基本上有一些參數我的每個子類都想要和其他一些人是特定。我不想在a的每個子類的定義中添加a,b。有什麼方法可以在python中執行此操作?

我想看到的是調用的能力:

b=B(a=1,b=2,c=3,d=4)  

,而不必包含A和B在子類中定義。

非常感謝!

回答

3
# Python 3, but the idea is the same in 2 

class A: 
    def __init__(self, a, b): 
     # ... 

class B(A): 
    def __init__(self, c, d, *args, **kwargs): 
     super().__init__(*args, **kwargs) 

class C(A): 
    def __init__(self, e, f, g, *args, **kwargs): 
     super().__init__(*args, **kwargs) 
相關問題