2014-11-21 105 views
1

我在Python中試驗父類和子類。我收到了一個我似乎無法解決的錯誤,錯誤和代碼都在下面發佈。如果你可以發佈爲什麼發生這種情況的原因,並編輯我的代碼如何解決這個問題,將不勝感激。父母和孩子班級意外的關鍵字參數

# Classes Example 
class vehicle(): 
    def __init__(self,name,weight,wheels,color): 
     self.name = name 
     self.weight = weight 
     self.wheels = wheels 
     self.color = color 
    def __str__(self): 
     return("Hi, iam a vehicle called " + self.name) 
    def wow(self): 
     return(self.weight/self.wheels) 

class car(vehicle): 

    def __init__(self,doors,quantity,mpg): 
     self.doors = doors 
     self.quantity = quantity 
     self.mpg = mpg 

    def distance(self): 
     return(self.quantity/self.mpg) 


# Main Program 
object1 = vehicle("Audi A3",1000,4,"blue") 
print(object1) 
print(object1.name) 
object1.name = "Audi S3" 
print(object1.name) 
print(object1.weight) 

object2 = vehicle(name = "Claud Butler" , color = "Red" , wheels = 2, weight = 20) 
print(object2) 
print(object2.wow()) 

object3 = car(name = "Burty", color = "Pink" , wheels = 3, weight = 500, doors = 3 , quantity = 10, mpg = 1000) 
print(object3.color) 
print(object3.wow()) 
print(object3.distance()) 

我得到以下錯誤:

Traceback (most recent call last): 
    File "H:\my documents\Computing\Class example.py", line 39, in <module> 
    object3 = car(name = "Burty", color = "Pink" , wheels = 3, weight = 500, doors = 3 , quantity = 10, mpg = 1000) 
TypeError: __init__() got an unexpected keyword argument 'name' 
+0

記住'__init__'就像任何其他的方法,並在版本'car'覆蓋在'vehicle'版本。 – RemcoGerlich 2014-11-21 13:43:43

+0

'__init__'和其他方法完全一樣,如果你把它放在車外,那麼它會使用車輛的'__init__'。剛剛測試過,看看我是不是瘋了... – RemcoGerlich 2014-11-21 14:31:15

回答

0

的方法

__init__(self,doors,quantity,mpg): 

沒有一個說法叫name。如果你想要它,你應該添加它。

1

將引發錯誤的下面一行:

object3 = car(name = "Burty", color = "Pink" , wheels = 3, weight = 500, doors = 3 , quantity = 10, mpg = 1000) 

在那裏,您呼叫的car構造函數(其中包括)一個name參數。現在,如果你看一下car類型的定義構造函數,你看到以下內容:

class car(vehicle): 
    def __init__(self,doors,quantity,mpg): 
     self.doors = doors 
     self.quantity = quantity 
     self.mpg = mpg 

正如你所看到的,有在參數列表中沒有name參數。

我假定您期望car子類繼承父類vehicle類的所有構造函數參數,但事實並非如此。除非你明確地複製這些參數,否則它們不會在那裏。你也必須明確地調用父類的構造函數。總而言之,你的car構造函數應該是這樣的:

def __init__(self, name, weight, wheels, color, doors, quantity, mpg): 
    # call the base type’s constructor (Python 3 syntax!) 
    super().__init__(name, weight, weels, color) 

    self.doors = doors 
    self.quantity = quantity 
    self.mpg = mpg