不使用继承的点类和矩形类

时间:2018-09-22 23:39:40

标签: python

我试图创建一个具有浮点值“ x”和“ y”的数据属性的点类,从而定义点在2D空间中的位置。另外,我想使用 init 方法,例如它是默认值x = 0和y = 0的初始化。然后是一个移动函数,将'x'和'y'作为新函数接受点的位置。最后是一个告诉点距离的函数。我想让它返回从此点到x,y的另一个点的欧几里得距离。怎么办?

这是我到目前为止用于上述说明的代码:

import math

class Point:

    def __init__(self):
        self.x = 0 # initialize to 0
        self.y = 0 # initialize to 0

    def move(self, x, y):
        self.x = x
        self.y = y 

可以在该点以及从该点到另一个点x,y的欧几里得距离上使用帮助。不确定到目前为止我是否有正确的想法。 python的新手,所以不知道如何测试此代码的功能。感谢您的帮助!

在那部分之后,我将能够在矩形的两个相对角处定义两个点,并使用上面定义的点,而无需使用继承。关于如何创建此类的任何想法?

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作(代码中的注释):

示例:

class Point:

    def __init__(self, x: float=0.0, y: float=0.0)-> None:   # assign default values
        self.x = x
        self.y = y

    def move_by(self, dx: float, dy: float)-> None:   # move Point by dx, dy
        self.x += dx
        self.y += dy 

    def move_to(self, new_x: float, new_y: float)-> None:   # relocate Point to new x, y position
        self.x = new_x
        self.y = new_y 

    def distance(self, other: 'Point')-> float:   # calculates and returns the Euclidian distance between self and other
        if isinstance(other, Point):
            x0, y0 = self.x, self.y
            x1, y1 = other.x, other.y
            return ((x1 - x0)**2 + (y1 - y0)**2) ** 0.5
        return NotImplemented

    def __str__(self)-> str:    # add a nice string representation
        return f'Point({self.x}, {self.y})'

测试:

p = Point(1, 2)
q = Point()
print(p, q, p.distance(q) == 5**0.5)
p.move_by(.1, -.1)
print(p)

输出:

Point(1, 2) Point(0.0, 0.0) True
Point(1.1, 1.9)

Rectangle类可能像这样: [已编辑以添加默认Point值]

Rectangle.__init__中,对作为参数提供的Points的x和y值的最小值和最大值进行排序,以确定确定矩形的左上和右下点

class Rectangle:
        def __init__(self, p0: Point=Point(), p1: Point=Point(1.0, 1.0))-> None:  # <--- [edit]: now with default values
        x0, y0 = p0.x, p0.y
        x1, y1 = p1.x, p1.y
        self.topleft = Point(min(x0, x1), max(y0, y1))      # calculate the topleft and bottomright
        self.bottomright = Point(max(x0, x1), min(y0, y1))  # of the bounding box

    def __str__(self)-> str:
        return f'Rectangle defined by bbox at: {self.topleft}, {self.bottomright})'

测试:

p = Point(1, 2)
q = Point()
print(p, q, p.distance(q) == 5**0.5)
p.move_by(.1, -.1)
print(p)

r = Rectangle(p, q)
print(r)

输出:

Point(1, 2) Point(0.0, 0.0) True
Point(1.1, 1.9)
Rectangle defined by bbox at: Point(0.0, 1.9), Point(1.1, 0.0))

[编辑:]带有矩形点的默认值:

s = Rectangle()
print(s)

输出:

Rectangle defined by bbox at: Point(0.0, 1.0), Point(1.0, 0.0))