我在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'
記住'__init__'就像任何其他的方法,並在版本'car'覆蓋在'vehicle'版本。 – RemcoGerlich 2014-11-21 13:43:43
'__init__'和其他方法完全一樣,如果你把它放在車外,那麼它會使用車輛的'__init__'。剛剛測試過,看看我是不是瘋了... – RemcoGerlich 2014-11-21 14:31:15