【发布时间】:2022-10-06 03:51:26
【问题描述】:
当我尝试这段代码时,我在 Python 中得到了 AttributeError 。我花了将近 1 小时才弄清楚,但我做不到。我已经编写了计算矩形面积、三角形面积和圆半径的代码,然后我在 Shape 类中为矩形、三角形和圆形创建了 3 个函数。当我运行此代码时,我得到 AttributeError 并且它说的 \'Project\' 对象对于我选择的任何形状都没有属性 \'rectangle\'。
class Project:
def __init__(self):
print(\"1. Area if rectangle\")
print(\"2. Area of a triangle\")
print(\"3. Radius of a circle\")
print(\"4. Quit!\")
while True:
try:
selection = int(input(\"Enter your choice \"))
if selection == 1:
self.rectangle()
elif selection == 2:
self.triangle()
elif selection == 3:
self.circle()
elif selection == 4:
break
else:
print(\"Invalid value. Select 1-4\")
except ValueError:
print(\"Invalid value. Select 1-4. (NO ALPHABETIC LETTERS)\")
class shape:
def rectangle(self):
base = int(input(\"Enter the base:\"))
height = int(input(\"Enter the height\"))
area = height * base
print(f\"The area of a rectangle is {area}\")
def triangle(self):
base = int(input(\"Enter the base: \"))
height = int(input(\"Enter the height: \"))
area = base * height / 2
print(f\"The are of the triangle is {area}\")
def circle(self):
radius = int(input(\"Enter the Radius: \"))
area = 3.142 * radius * radius
print(f\"The area of the circle is {area}\")
Project()
-
为什么您期望
Project对象应该具有rectangle、triangle或circle中的任何一个?
标签: python python-3.x attributeerror