简体   繁体   English

在实例方法的返回值上调用的__str__方法

[英]__str__ method called on return values of instance methods

I am developing a module that draws lines and finds their midpoints. 我正在开发一个画线并找到其中点的模块。 For purposes of testing, I want to create some string outputs from the relevant classes. 为了进行测试,我想从相关类中创建一些字符串输出。

class Line:
  def __init__(self, endpoints):
    self.start = endpoints[0]
    self.end = endpoints[1]

  def midpoint():
    x = (start.getX + end.getX) / 2.0
    y = (start.getY + end.getY) / 2.0
    return Point(x, y)

  def __str__(self):
    return "line from " + `self.start` + " to " + `self.end` + "."

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

  def getX():
    return x

  def getY():
    return y

  def __str__(self):
    return "[" + str(self.x) + ", " + str(self.y) + "]"

  __repr__ = __str__

point1 = Point(4,5)
point2 = Point(0,0)
line1 = Line([point1, point2])

print line1
print line1.midpoint

Expected output: 预期产量:

line from [4, 5] to [0, 0]
[2.0, 2.5]

Instead I get: 相反,我得到:

line from [4, 5] to [0, 0]
<bound method Line.midpoint of <__main__.Line instance of 0x105064e18>>

How can I get the expected string representation of the midpoint, which is being returned as an instance of the Point class? 如何获得预期的中点字符串表示形式,该中点作为Point类的实例返回?

You are printing the method itself, not the returned value of the method. 您正在打印方法本身,而不是方法的返回值。 Change your last line to this: 将最后一行更改为此:

print line1.midpoint()

Also, the first definition line of your method should use self as the only parameter, like so: 同样,方法的第一条定义行应使用self作为唯一参数,如下所示:

def midpoint(self):

The same applies to the rest of the methods, they should have self as a parameter (Point.getX and Point.getY). 其余方法同样如此,它们应将self作为参数(Point.getX和Point.getY)。

In the midpoint method, you should have start.getX(), start.getY(), end.getX(), and end.getY() should have "self." 在中点方法中,您应该具有start.getX(),start.getY(),end.getX()和end.getY()应该具有“自我”。 in front of it. 在它前面。 You should also have "self" as a parameter for the method for every method in a class. 对于类中的每个方法,还应该将“ self”作为方法的参数。

midpoint method 中点法

I will paste the entire code below to show you exactly what I have done. 我将在下面粘贴整个代码,以向您确切显示我所做的事情。

entire code 整个代码

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

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