【问题标题】:I'm getting AttributeError in Python我在 Python 中得到 AttributeError
【发布时间】: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


【解决方案1】:

因为矩形在 Shape 类上,而不是在 Project 类上。您需要实例化一个形状shape = Shape(),然后在其上调用rectangle:shape.rectangle()

【讨论】:

    【解决方案2】:

    矩形是形状类的方法;它不是项目类的一部分。

    它应该看起来像这样。

    if selection == 1:
        s = shape()
        s.rectangle()
    

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-23
      • 2017-10-26
      相关资源
      最近更新 更多