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 + " Filled: " + str(self.__filled)
这是Triangle课程:
from GeometricObject import GeometricObject
class Triangle(GeometricObject):
def __int__(self,side1=1.0,side2=1.0,side3=1.0):
super().__init__()
self.__side1=side1
self.__side2=side2
self.__side3=side3
def getPerimeter(self):
return self.__side1 + self.__side2 + self.__side3
def __str__(self):
return super().__str__()+" side 1: "+str(self.__side1)+" side 2: "+str(self.__side2)+" side 3: "+str(self.__side3)
from triangle import Triangle
from GeometricObject import GeometricObject
def main():
side1=int(input("Enter first side: "))
side2=int(input("Enter second side: "))
side3=int(input("Enter third side: "))
t1=Triangle(side1,side2,side3)
print(t1.getColor())
print(t1.getPerimeter())
print(t1.__str__())
main()
在main函数中创建三角形对象t1时发生错误: init ()需要1到3个位置参数,但是给出了4个...
我知道还有其他关于类似错误的帖子,但是如果你提供的参数不够多,那么提供太多参数的那些就没有回答我的问题。
答案 0 :(得分:4)
您需要将__int__
更改为__init__
,并且只能通过super()
self
。
class Triangle(GeometricObject):
def __init__(self,side1=1.0,side2=1.0,side3=1.0):
#The correct alternative to below is:
#super(GeometricObject, self).__init__()
GeometricObject.__init__(self)
self.__side1=side1
self.__side2=side2
self.__side3=side3
要回答你的第二个问题,这是一个例子:
class A(object):
def __init__(self, color = 'blue'):
self.color = color
def __str__(self):
return str(self.color)
class B(A):
def __init__(self, name = 'steve'):
A.__init__(self)
self.name = name
def __str__(self):
#alternatively: return super(B, self).__str__() + " " + str(self.name)
return A.__str__(self) + " " + str(self.name)
打印"blue steve"
答案 1 :(得分:1)
Triangle的 init 函数拼写错误为__int__
:
def __int__(self,side1=1.0,side2=1.0,side3=1.0):
更改为:
def __init__(self,side1=1.0,side2=1.0,side3=1.0):
适合我!