gpt4 book ai didi

python - 使用 super() 缺少父类(super class)的参数

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

我收到错误,来自 GeometricObject 的颜色和填充参数未传递给 Triangle 对象,但不确定原因。我尝试了 2 种方法,更喜欢使用 super()

在最后一行,当我尝试使用用户输入获取Triangle 时,出现错误:

TypeError: __init__() takes from 1 to 4 positional arguments but 6 were given
import math
import sys

class GeometricObject:
def __init__(self, color = "green" , filled = True):
self.__color = color
self.__filled = filled

def getColor(self):
return self.__color

def setColor(self, color):
self.__color = color

def isFilled(self):
return self.__filled

def setFilled(self, filled):
self.__filled = filled

def __str__(self):
return "color: " + self.__color + \
" and filled: " + str(self.__filled)


class Triangle(GeometricObject):
def __init__(self, side1 = 1.0, side2 = 1.0, side3= 1.0):
GeometricObject.__init__(self)
#super().__init__(color, filled)
self.__side1 = side1
self.__side2= side2
self.__side3 = side3

def get_side1(self):
return self.__side1
def set_side1(self, side1):
self.__side1 = side1

def get_side2(self):
return self.__side2
def set_side2(self, side2):
self.__side2 = side2

def get_side3(self):
return self.__side3
def set_side3(self, side3):
self.__side3 = side3

def get_area(self):
p = self.get_perimeter() / 2
area = math.sqrt(
p *
(p - self.__side1) *
(p - self.__side2) *
(p - self.__side3)
)
return area

def get_perimeter(self):
return self.__side1 + self.__side2 + self.__side


def __str__(self):
info = "Triangle: side1 = {} side2 = {} side3 = {}".format(
self.__side1, self.__side2, self.__side3
)
return info




if __name__ == "__main__":
float_sides = []
sides = input("Enter numeric values for sides 1, 2, and 3\
separated by commas: ").split(",")
try:
for e in sides:
float(e)
float_sides.append(e)
except:
print("Invalid input, try again.")
sys.ext()
if len(float_sides) !=3:
print("Invalid number of inputs, try again")
sys.ext()

side1 = float_sides[0]
side2 = float_sides[1]
side3 = float_sides[2]

color = input('Enter color: ')
filled = input('Enter 1 if triangle is filled or 0 if it is not: ')
if filled not in (1,0):
print("Invalid input, try again")
#sys.ext()

triangle = Triangle(side1, side2, side3, color, filled)

最佳答案

您需要在三角形的 __init__ 中包含 colorfilled,然后将其传递给 super:

class Triangle(GeometricObject):
def __init__(self, side1=1.0, side2=1.0, side3= 1.0, color=None, filled=None):
super().__init__(color, filled)
...

关于python - 使用 super() 缺少父类(super class)的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59236600/

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