0

Why does changing the str method affect other methods? It seems like changing the __str__method also changes the other methods that return a Point2d object.

import math

class Point2d(object):
    def __init__( self, x0, y0 ):
        self.x = x0
        self.y = y0   

    def magnitude(self):
        return math.sqrt(self.x**2 + self.y**2)

    # 2.1
    def __str__(self):
        #return str((self.x, self.y))
        return 'self.x, self.y'

    # 2.2
    def __sub__(self, other):
        return Point2d(self.x - other.x, self.y - other.y)


    # 2.4
    def __eq__(self, other):
        if self.x == other.x and self.y == other.y:
            return True

p = Point2d(0,4)
q = Point2d(5,10)
r = Point2d(0,4)
leng = Point2d.magnitude(q)
print("Magnitude {:.2f}".format( leng ))
print(p.__str__(), type(p.__str__())) # 2.1  
print(p-q) # 2.2
print(Point2d.__sub__(p,q))  # 2.2 same as line above (line 60).
print(p.__eq__(r))

Expected results:

Magnitude 11.18
self.x, self.y <class 'str'>
(-5, -6)
(-5, -6)
True

Actual results:

Magnitude 11.18
self.x, self.y <class 'str'>
self.x, self.y
self.x, self.y
True

2 Answers2

1

When you call print(something), the __str__ method of something is called:

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

So your changes don't really affect every other function, they affect how they are printed. If you will launch your code in Jupyter notebook and will remove print word, you will see your Point2d object.

vurmux
  • 9,420
  • 3
  • 25
  • 45
1

__str__() is a "special" method. You'll notice that

print(p.__str__())

and

print(p)

give you the same result.

Since __sub__() (and all similar functions) return their result,

print(p-q) # 2.2

is the same as

z = p - q
print(z)

which, as we said, is the same as

print(z.__str__())
Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25