簡體   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