I want to be able to create a rectangle where it has the data attribute of two points defining two opposite corners of a rectangle as, use the Points defined above, not using inheritance. But I am having trouble with the initialization method in the rectangle class and a few methods and not sure if I am going about this the correct way. I want the init : initialize with default p1 = (0,0), p2 = (1,1)
Here is what I have so far for the Point class:
import math
class Point:
def __init__(self, x: float = 0.0, y: float = 0.0)->None:
self.x = x # initialize to 0
self.y = y # initialize to 0
def moveIt(self, dx: float, dy: float)-> None:
self.x = self.x + dx
self.y = self.y + dy
def distance(self, otherPoint: float):
if isinstance(otherPoint, Point):
x1 = self.x
y1 = self.y
x2 = otherPoint.x
y2 = otherPoint.y
return ( (x1 - x2)**2 + (y1 - y2)**2 )**0.5
This all appears to work as expecte when I create a point.
p1 = Point()
print(p1.x, p1.y)
>>>> 0 0
But my Rectangle class is not working when I create a blank Rectangle object. Here is the code:
class Rectangle:
def __init__(self, topLeft, bottomRight):
self.topLeft = 0,0
self.bottomRight = 1,1
I can't seem to find a way to have like I had it in the Point class where the Point is initialized from the get go to x=0, and y=0. Is there any way to do this in the Rectangle class? I tried the following but it wasn't allowed:
Class Rectangle:
def __init__(self, topLeft = (0,0), bottomRight = (1,1)):
self.topLeft = topLeft
self.bottomRight = bottomRight
When I run the code I get errors that I cannot initialize like this.
r1 = Rectangle()
print(r1.topLeft, r1.bottomRight)
After the initialization I want to be able to pass in Points I made.
Finally, from this I am trying to create two methods Get_area to return the area of the rectangle as a floating point value and Get_perimeter to return the perimeter as a floating point value.
The problem is that you wrote Class
instead of class
. Your code works fine when it is rectified
You wrote
Class Rectangle:
You should write
class Rectangle:
Complete:
class Rectangle:
def __init__(self, topLeft = (0,0), bottomRight = (1,1)):
self.topLeft = topLeft
self.bottomRight = bottomRight
r1 = Rectangle()
print(r1.topLeft, r1.bottomRight)
> (0, 0) (1, 1)
Use the following way to override the default values
r1 = Rectangle(topLeft = (0,0.5), bottomRight = (1,1))
Edit 2: Overriding the defaults
p1 = (3,5)
p2 = (6,10)
r1 = Rectangle()
print (r1.topLeft, r1.bottomRight)
> (0, 0) (1, 1)
r2 = Rectangle(p1, p2)
print (r2.topLeft, r2.bottomRight)
> (3, 5) (6, 10)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.