1.
Suppose you have a Rectangle object and wish to create a new rectangle that has been scaled by some amount. For example, a 3 by 5 rectangle scaled up by a factor of two would be 6 by 10. A rectangle with width 24 and height 18 scaled by a factor of one-third would have a width of 8 and a height of 6. We would like to write a method called
scale
that takes a factor as a parameter and returns the scaled Rectangle
.
Solution.
class Rectangle:
""" Rectangle class for representing and manipulating width and height. """
def __init__(self, init_width, init_height):
""" Create a new point at the given coordinates. """
self.width = init_width
self.height = init_height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
def diagonal_length(self):
return ((self.width ** 2) + (self.height ** 2)) ** 0.5
def __str__(self):
return f"width={self.width}, height={self.height}"
def scale(self, factor):
width = self.width * factor
height = self.height * factor
return Rectangle(width, height)
r1 = Rectangle(3, 5)
big_r1 = r1.scale(2)
print(big_r1)
r2 = Rectangle(24, 18)
small_r2 = r2.scale(1 / 3)
print(small_r2)