简体   繁体   中英

__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?

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:

def midpoint(self):

The same applies to the rest of the methods, they should have self as a parameter (Point.getX and Point.getY).

In the midpoint method, you should have start.getX(), start.getY(), end.getX(), and end.getY() should have "self." in front of it. You should also have "self" as a parameter for the method for every method in a class.

midpoint method

I will paste the entire code below to show you exactly what I have done.

entire code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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