簡體   English   中英

Python-點類未獲得正確的輸出

[英]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.point0self.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 point0point1線實例值分別指向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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM