简体   繁体   English

Python-点类未返回正确点

[英]Python - point class not returning correct points

So I have a point class where I declare a point and then perform operations on it. 因此,我有一个Point类,在其中声明一个点,然后对其进行操作。 One of the operations is scale which takes in a point and scales it while raising an error if the point is not a float value. 如果点不是浮点值,则操作之一就是缩放,该操作会获取一个点并对其进行缩放,同时引发错误。 Here's what it looks like: 看起来是这样的:

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

And if I test it with this test code: 如果我使用以下测试代码进行测试:

  print '*** scale'
# f illegal
try:
    p0 = Point(0.0, 0.0)
    p0.scale(1)
except Error as e:
    print 'caught:', e.message

# normal case
p0 = Point(2.0, 3.0)
p0.scale(2.3)
print p0

Then the output I get is: 然后我得到的输出是:

*** scale
caught: Parameter "f" illegal.
2 3

But the output that I want is: 但是我想要的输出是:

*** scale
caught: Parameter "f" illegal.
5 7

So the error message looks fine but the values that it's printing out are not. 因此,错误消息看起来不错,但打印出来的值却不正确。 So why doesn't it print out the correct values? 那为什么不打印出正确的值呢? Here's my init and str methods: 这是我的initstr方法:

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 __str__(self):
    return '%d %d' % (int(round(self.x)), int(round(self.y)))

You are assigning to new attributes : 您正在分配新属性

self.x0 = f * self.x
self.y0 = f * self.y

x0 and y0 are different attributes from x and y . x0y0是与xy不同的属性。 Thus, x and y remain unchanged. 因此, xy保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM