gpt4 book ai didi

python - 父类和子类意外的关键字参数

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:58 25 4
gpt4 key购买 nike

我正在尝试使用 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'

最佳答案

以下行中引发错误:

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

在那里,您将使用(其中包括)name 参数调用 car 构造函数。现在,如果您查看 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

关于python - 父类和子类意外的关键字参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27062155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com