[英]Python - point class not getting correct output
所以我有一個點類和一個線類,它們都有一個scale方法。
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 23。那為什么它卻打印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
分配給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)
您可以查看此問題以獲取更多信息。
將p0,p1
乘以2后將打印line
乘以x,y
對,即p0, p1
。 point0
和point1
線實例值分別指向p0和p1的Point
實例,作為print line
結果,您可以看到每個點的x,y
的更新值。
p0 = Point(0,1)
p1 = Point(2,3)
line = Line(p0, p1)
print line # 0 1 2 3
p0.scale(2.0)
p1.scale(2.0)
print line # 0 2 4 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.