Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Problem Definitions in regards to Classes [closed]

Tags:

python

# This Program generates a class that is aimed at finding the Area and Perimeter
# in a rectangle.

import math

class Rectangle:
    def __init__(self, height, width):
        self.width = 2
        self.height = 1

    def getArea(self):
        area = self.width * self.height
        return area

    def getPerimeter(self):
        perimeter = 2 * (self.width + self.height)
        return perimeter

    def setHeight(self, height):
        self.height = height

    def setWidth(self, height):
        self.width = width

def main():
    rectangle1 = Rectangle()
    print("The area of the Rectangle of radius" , Rectangle1.width, Rectangle1.height, "is",\
          Rectangle1.getArea())
main()

The following Code is in Python. So far the only issue I have at the moment is that when I go to run it it says that the name "Rectangle" is not defined. This is in reference to rectangle1 = Rectangle() in which it is assigned to the class and all of the various instances and methods that it has listed above.

But because of this definition issue, I cant use the Rectangle class's contents. Where am I going wrong?

like image 863
Najah Johnson Avatar asked Mar 02 '23 13:03

Najah Johnson


2 Answers

There are so many error in your program.

  1. function init takes two argument, and you are not providing any argument while creating object Rectangle()

  2. function setWidth(self, height), and inside function you are using variable width.

  3. Python is case sensitive, so rectangle is different from Rectangle, In the caller place, Your object name is 'rectangle1', while you are calling it with Rectangle1

If you fix these your program should work

like image 56
Shivam Seth Avatar answered Mar 15 '23 11:03

Shivam Seth


There are multiple mistakes. You are calling Rectangle class without height and width (you could also pass them as default parameters).

Your indentation is broken in the class.

You have initialized rectangle1 but calling Rectangle1, hence the additional errors.

import math

class Rectangle:
  def __init__(self, height, width):
      self.width = 2
      self.height = 1

  def getArea(self):
      area = self.width * self.height
      return area

  def getPerimeter(self):
      perimeter = 2 * (self.width + self.height)
      return perimeter

  def setHeight(self, height):
      self.height = height

  def setWidth(self, height):
      self.width = width

def main():
    rectangle1 = Rectangle(4,2)
    print("The area of the Rectangle of radius" , rectangle1.width, rectangle1.height, "is",\
          rectangle1.getArea())
main()
like image 26
Zabir Al Nazi Avatar answered Mar 15 '23 10:03

Zabir Al Nazi