Python - 点类没有得到正确的输出

标签 python

所以我有一个点类和一个线类,它们都有一个比例方法。

class Point:

    def __init__(self, x, y):
        if not isinstance(x, float):
            raise Error("Parameter \"x\" illegal.")
        self.x = x
        if not isinstance(y, float):
            raise Error ("Parameter \"y\" illegal.")
        self.y = y

    def scale(self, f):
        if not isinstance(f, float):
            raise Error("Parameter \"f\" illegal.")
        self.x = f * self.x
        self.y = f * self.y

    def __str__(self):
        return '%d %d' % (int(round(self.x)), int(round(self.y)))

class Line:

    def __init__(self, point0, point1):
        self.point0 = point0
        self.point1 = point1

    def scale(self, factor):
        if not isinstance(factor, float):
            raise Error("Parameter \"factor\" illegal.")
        self.point0.scale(factor)
        self.point1.scale(factor)

    def __str__(self):
        return "%s %s" % (self.point0, self.point1)

因此,我对此代码所做的测试之一是检查我在此测试代码中所做的浅拷贝。

p0.scale(2.0)
p1.scale(2.0)
print line

问题是打印行给了我 0 2 4 6,它应该给我 0 1 2 3。那么为什么它打印 2 的倍数呢? scale 方法应该返回缩放后的值,对于所有其他测试用例,它会打印预期值,但是仅使用此测试代码,它就会打印我没想到的值。 p0 和 p1 的值设置方式如下:

print '********** Line'
print '*** constructor'
p0 = Point(0.0, 1.0)
p1 = Point(2.0, 3.0)
line = Line(p0,p1)
print line

最佳答案

Line__init__ 方法中,您分配名称 self.point0self.point1到传入的两个点。这不会创建新副本,只会为内存中的对象提供另一个名称。如果将此方法更改为

def __init__(self, point0, point1):
    self.point0 = Point(point0.x, point0.y)
    self.point1 = Point(point1.x, point1.y)

然后一切都应该按预期进行。或者,您可以使用复制模块:

from copy import copy

class Line:
    def __init__(self, point0, point1):
        self.point0 = copy(point0)
        self.point1 = copy(point1)

您还可以在 Point 类上定义自己的 __copy____deepcopy__ 方法。

def __copy__(self):
    return type(self)(self.x, self.y)

def __deepcopy__(self, memo):
    return type(self)(self.x, self.y)

您可以查看this question了解更多信息。

关于Python - 点类没有得到正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35907131/

相关文章:

python - 如何让Python将函数识别为生成器函数?

python - 更新 matplotlib 中颜色条的范围

python - 如何使用python opencv在jupyter笔记本上以正常速度播放mp4

python - Keras:使用 flow_from_directory 的 fit_generator 的多个输入

python - 使用 Django 在两个日期之间进行选择

python - 应该将 Python 记录器作为参数传递吗?

python - 在 python 中使用 beautifulsoup 单击链接

python - Flask:在模板中渲染 unicode 字符

python - 如果数据框中列表中的任何值在另一个列表中,则过滤 Pandas 数据框行

python - 如何格式化符合 PEP8 的 python 断言语句?