Home > Software engineering >  I'm getting AttributeError in Python
I'm getting AttributeError in Python

Time:10-06

When I try this code I'm getting AttributeError in Python. I've spent almost 1h to figures out, but I can't. I've code to calculate the area of a rectangle, area of a triangle and the radius of the circle, then I created 3 function in class Shape for rectangle , triangle and circle. When I run this code I'm getting AttributeError and its say's 'Project' object has no attribute 'rectangle' for whatever shape I choose.

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()

screenshot of the AttributeError

CodePudding user response:

Because rectangle is on the Shape class, not the Project class. You need to instantiate a shape shape = Shape(), and then call rectangle on it: shape.rectangle()

CodePudding user response:

rectangle is a method of the shape class; it is not part of the project class.

It should look something like this.

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