如何用python中的topLeft点(0,0)和bottomRight点(1,1)两点初始化矩形类?

时间:2018-09-23 17:44:05

标签: python

我希望能够创建一个矩形,在该矩形中具有定义矩形的两个相对角的两个点的数据属性,请使用上面定义的点,而不要使用继承。但是我在矩形类中的初始化方法和一些方法上遇到了麻烦,不确定我是否要以正确的方式进行操作。我想要 init :使用默认p1 =(0,0),p2 =(1,1)

进行初始化

这是我到目前为止为Point类提供的内容:

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

当我创建一个点时,所有这些似乎都可以正常工作。

p1 = Point()

print(p1.x, p1.y)

>>>> 0 0

但是当我创建一个空白的Rectangle对象时,我的Rectangle类不起作用。这是代码:

class Rectangle:
    def __init__(self, topLeft, bottomRight):
        self.topLeft = 0,0
        self.bottomRight = 1,1

我似乎无法找到一种方法,就像我在Point类中那样,将Point从get go初始化为x = 0和y = 0。在Rectangle类中有什么方法可以做到这一点?我尝试了以下操作,但不允许:

Class Rectangle:
    def __init__(self, topLeft = (0,0), bottomRight = (1,1)):
        self.topLeft = topLeft
        self.bottomRight = bottomRight

运行代码时,出现无法初始化的错误。

r1 = Rectangle()

print(r1.topLeft, r1.bottomRight)

初始化之后,我希望能够传递我的得分。

最后,我正在尝试创建两个方法Get_area来返回矩形的面积作为浮点值,并创建Get_perimeter来返回周长作为浮点值。

1 个答案:

答案 0 :(得分:0)

问题是您写了Class而不是class。修改后的代码可以正常工作

Class Rectangle:

应该

class Rectangle:

完成:

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)

使用以下方法覆盖默认值

r1 = Rectangle(topLeft = (0,0.5), bottomRight = (1,1))

编辑2:覆盖默认值

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)