2013-10-24 112 views
0

我面臨着超類屬性值繼承的不能。我已經調用超類的構造函數,現在試圖檢查出繼承的值。Python:類數據的繼承(如果超類對象已經被初始化)

class base: 
    def __init__(self, x): 
     self.x = x 
     print(self.x) 

class derive(base): 
    def __init__(self): 
     print(self.x + 1) 


print("base class: ") 
b = base(1)       <-- Creating superclass instance 
print("derive class: ") 
d = derived()       <-- Inheriting. Failure. 

爲什麼我不能這樣做?爲了得到x屬性,我是否應該明確地將底層對象傳遞給繼承對象?

+2

您需要從派生類中調用基類「__init__」。關於這個問題有很多以前的問題。 – BrenBarn

+0

可能的重複[如何在Python中使用'超'?](http://stackoverflow.com/questions/222877/how-to-use-super-in-python) – shx2

+0

@ shx2:這個問題是Python 2 - 具體的答案。 –

回答

2

bd是無關的; b完全是單獨的基類的實例。

如果要調用被覆蓋的初始化(__init__),然後使用super() proxy object訪問它:

class derive(base): 
    def __init__(self): 
     super().__init__(1) 
     print(self.x + 1) 

請注意,您仍然需要一個參數傳遞給父類的初始化通過。在上面的例子中,我爲父初始值設定項的參數x傳入一個常數值1。

請注意,我在這裏使用了Python 3特定語法;不帶參數的super()在Python 2中不起作用,在Python 2中,您還需要使用object作爲base類的父項,以使其成爲新式類。

+1

您應該提到它在Python 2中不起作用。 – zero323

+0

@ zero323:OP使用'print()'函數;出於這個原因,我堅持使用Python 3。 –

+0

有時我覺得自己是唯一一個使用'print()'和Python 2.x – zero323