from math import *
class GeometricObject():
def __init__(self, color = "green", filled = True):
self.color = color
self.filled = filled
def __str__(self):
return "color: " + self.__color + \
" and filled: " + str(self.__filled)
class Triangle(GeometricObject):
def __init__(self, side1 = 1, side2 = 1, side3 = 1):
super().__init__()
self.side1 = float(side1)
self.side2 = float(side2)
self.side3 = float(side3)
def getArea(self):
return self.area
def setArea(self, side1, side2, side3):
s = (side1 + side2 + side3)/2
area = sqrt(s*(s-side1)*(s-side2)*(s-side3))
self.area = area
def getPerimeter(self):
return self.perimeter
def setPerimeter(self, side1, side2, side3):
perimeter = side1 + side2 + side3
self.perimeter = perimeter
def __str__(self):
return "Triangle: " + "side 1 = " + str(self.side1)+ \
" " + "side 2 = " + str(self.side2) + " " + \
"side 3 = " + str(self.side3)
def main():
side1 = eval(input("Enter a value for side 1: "))
side2 = eval(input("Now enter a value for side 2: "))
side3 = eval(input("Now enter a value for side 3: "))
color = input("Enter the color of the triangle: ")
filled = input("Enter true(filled) or false(not filled) " + \
"for the triangle being filled: ")
go = GeometricObject(color, filled)
tri = Triangle(side1, side2, side3)
tri.setArea(side1, side2, side3)
tri.setPerimeter(side1, side2, side3)
print("\n\n")
print("A Triangle: ", tri.__str__(), go.__str__())
print("The area is: ", tri.getArea())
print("The perimeter is: ", tri.getPerimeter())
main()
以上是我的代码和我得到的错误我不明白,大部分代码都直接来自书中的示例并进行了调整以适合我的程序。我能做些什么来让我按照我需要的方式工作。这是用于家庭作业,我可以真正使用一些帮助来找出我的代码中的错误。
这不是一个错误但是如何在其他三角形信息之后显示GeometricObject颜色和填充属性。
Enter a value for side 1: 3
Now enter a value for side 2: 4
Now enter a value for side 3: 5
Enter the color of the triangle: blue
Enter 1(filled) or 0(not filled) for the triangle being filled: 1
A Triangle: Triangle: side 1 = 3.0 side 2 = 4.0 side 3 = 5.0 <__main__.GeometricObject object at 0x000000000312EA20>
The area is: 6.0
The perimeter is: 12
答案 0 :(得分:1)
问题是tri.__str__
中的实例变量未被正确访问。
要访问属于该类实例的变量,您需要在名称前添加self.
函数中的变量名称也不正确:它们应该是__side1
,__side2
和__side3
。
将__str__
函数替换为此函数,它应该可以正常工作:
def __str__(self):
return "Triangle: " + "side 1 = " + str(self.__side1) +\
"side 2 = " + str(self.__side2) + "side 3 = " + str(self.__side3)
答案 1 :(得分:1)
你的问题在于这个功能:
def __str__(self):
return "Triangle: " + "side 1 = " + str(side1) +\
"side 2 = " + str(side2) + "side 3 = " + str(side3)
NameError表示它无法识别变量'side1',因为'side1'从未在该范围内声明。
现在,一个问题:side1,side2和side3从哪里被引用?你怎么能改变它们?