在以下用Python编写的脚本中,我想做的是计算圆形,正方形和矩形的面积。其中,我想实现从square.py到rectangle.py的继承。但是,我的继承实现失败,需要一些帮助来解决此问题。
当我尝试计算矩形的面积时,记录了以下错误消息。
int
script.py
Traceback (most recent call last):
File "script.py", line 28, in <module>
print(rectangle.sqArea())
File "/home/yosuke/Dropbox/Coding_dir/Python/Originals/OOP/Mathmatics/testdir2/rectangle.py", line 8, in sqArea
return self.length * self.height
AttributeError: 'Rectangle' object has no attribute 'length'
circle.py
from circle import Circle
from square import Square
from rectangle import Rectangle
category = {1:"Shapes", 2:"DST"}
for k,v in category.items():
print(k, v)
catNum = int(input("Type a category by number>> "))
if catNum == 1:
print("You chose shapes")
shapeDict = {1:"Circle", 2:"Square"}
for k,v in shapeDict.items():
print(k, v)
shapeNum = int(input("Select a shape by number>> "))
if shapeNum == 1:
radius = int(input("type a number>> "))
circle1 = Circle(radius)
print(circle1.cirArea())
if shapeNum == 2:
length = int(input("Type the length>> "))
square = Square(length)
print(square.sqArea())
print("Let's try rectangle too")
height = int(input("Type the height>> "))
rectangle = Rectangle(height)
print(rectangle.sqArea())
if catNum == 2:
print("Not yet finished!")
square.py
class Circle:
def __init__(self, radius):
self.radius = radius
def cirArea(self):
return self.radius * self.radius * 3.14
rectangle.py
class Square:
def __init__(self, length):
self.length = length
def sqArea(self):
return self.length * self.length
答案 0 :(得分:0)
您忘记了调用超类的__init__
。
class Rectangle(Square):
def __init__(self, height):
super().__init__(height)
答案 1 :(得分:0)
您的矩形的构造函数仅接收高度,并且仅设置其height属性。没有长度。
在Rectangle中,这样的事情可能起作用:
def __init__(self, length, height):
super().__init__(length)
self.height = height
但是您的课程很奇怪。矩形不是正方形,正方形是矩形。因此,如果有的话,继承应该在另一个方向上起作用。
但是我认为您很快就会遇到问题。事实证明,面向对象的编程不能很好地对这类事物进行建模,实际上,不同形状之间没有太多共享之处。