所以我有一个点类和一个线类,它们都有一个比例方法。
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.point0
和 self.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/