Reputation: 117
So for a point class I'm writing, I need to write a method that rounds and converts to an int in string form. This is what I did:
def __str__(self):
return int(round(self.x))
So it rounds and converts to an int but it isn't in string form. I've tried using str but that doesn't work at all. So how can I get that to string form? Here's my entire point class:
import math
class Error(Exception):
def __init__(self, message):
self.message = message
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 rotate(self, a):
if not isinstance(a, float):
raise Error("Parameter \"a\" illegal.")
self.x0 = math.cos(a) * self.x - math.sin(a) * self.y
self.y0 = math.sin(a) * self.x + math.cos(a) * self.y
def scale(self, f):
if not isinstance(f, float):
raise Error("Parameter \"f\" illegal.")
self.x0 = f * self.x
self.y0 = f * self.y
def translate(self, delta_x, delta_y):
if not isinstance(delta_x, float):
raise Error ("Parameter \"delta_x\" illegal.")
self.x0 = self.x + delta_x
if not isinstance(delta_y, float):
raise Error ("Parameter \"delta_y\" illegal.")
self.y0 = self.y + delta_y
def __str__(self):
return str(int(round(self.x)))
return str(int(round(self.y)))
Now I also have a line class that I haven't finished writing yet so if this class looks fine then the error must be in my line class.
Upvotes: 0
Views: 3162
Reputation: 84
Just cast the value you return into string. In the Python data model,
object.__str__(self)
Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.
From Python Data Model
The __str__
function is a built in function that must return a informal string representation for the object. You are returning an Integer representation.
So just change your return
to str(int(round(self.x)))
Upvotes: 1
Reputation: 2691
class X:
def __init__(self):
self.x = 3.1415
def __str__(self):
return str(int(round(self.x)))
x = X()
print x
This does print 3
Upvotes: 3