繁体   English   中英

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

[英]How does one initialize a rectangle class with two points, topLeft point (0,0) and bottomRight point (1,1) in 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初始化为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来返回周长作为浮点值。

问题是您写的是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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM