我認爲這將用一個例子來最好的解釋。
現在採取這樣的場景:
>Vehicle ---> Car,Bike,Boat,Aeroplane,Train
>[All are vehicles right]
>Things they have in common would be (say for ex.) **Price** and **Color**
然而的事情,他們不會有共同的會是什麼?
>**Wheels**. The total number of wheels may differ.
>
> Car-4 Bike-2 Boat-0 Aeroplane-(**Not sure**) Train-(**Many I
guess**?)
但你明白了嗎?所以,當我想只是有一個車輛對象我不希望(或我不能告訴的輪數)在這種情況下,我只能用剛剛價格和顏色初始化
然而當我知道具體類型車輛說車現在我可以__init__
它與輪數。現在,這是特定於對象的初始化發揮重要作用的地方。
上述樣品的完整的示例代碼:
class Vehicle():
def __init__(self, x, y):
self.color = y
self.price = x
def Horn(self):
print("Pommm...Pommmmm!!")
class Car(Vehicle):
def __init__(self, x, y,wheel):
Vehicle.__init__(self, x, y)
self.wheel = "Four Wheels man: 4"
class Scooter(Vehicle):
def __init__(self, x, y,wheel):
Vehicle.__init__(self, x, y)
self.wheel = "Just Two man : 2"
VehObj = Vehicle("5000$","Black")
VehObj.Horn()
print(VehObj.color,VehObj.price)
#However note this
carObj = Car("5000$","Black",4)
print(carObj.color,carObj.price,carObj.wheel)
#Look at this
sObj = Scooter("5000$","Black",2)
print(sObj.color,sObj.price,sObj.wheel)
輸出:
Pommm...Pommmmm!!
Black 5000$
Black 5000$ Four Wheels man: 4
Black 5000$ Just Two man : 2
。希望清除你。
第二個不是絕對的繼承,因爲兩個類都不能從外部訪問。現在你已經改變了代碼 – Rahul
我認爲沒有什麼區別,因爲在第一個例子中,你基本上繞過了自己的類'init' –
我更喜歡第一個版本,因爲你可以_expand_ __init__'方法而不覆蓋繼承代碼 – Aemyl