I've been assig to do the class rectangle, the class has two instance variables: length and width of the rectangle, and the methods methods setLength(), getLength(), setWidth(), getWidth() and computeArea(). Do you have any idea to do this. Anyway i'm to to python.

Recommended Answers

Start by declaring a class named Rectangle. Write a constructor (an __init__() method) that accepts arguments self, length and width, and assign the latter two to self.length and self.width inside the constructor.

Jump to Post

All 3 Replies

A class does not compute an area, it has an area.

Start by declaring a class named Rectangle. Write a constructor (an __init__() method) that accepts arguments self, length and width, and assign the latter two to self.length and self.width inside the constructor.

This basic class example should send you on your Python way:

class Rectangle:
    # class constructor
    # supply it with initial length and width values
    # self refers to the instance
    def __init__(self, length, width):
        self.width = width
        self.length = length

    def setLength(self, length):
        self.length = length

    def show(self):
        print("rectangle has length = {}".format(self.length))
        print("rectangle has width = {}".format(self.width))


length = 10
width = 5
# create a class instance
rect = Rectangle(length, width)

# show initial setting
rect.show()

''' result >>
rectangle has length = 10
rectangle has width = 5
'''

print('-'*40)  # a line of  dashes
# now set length to another value
rect.setLength(17)

# show new setting
rect.show()

''' result >>
rectangle has length = 17
rectangle has width = 5
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.