Python-如何以字符串形式返回int?

Python-如何以字符串形式返回int?,python,Python,因此,对于我正在编写的point类,我需要编写一个方法,将其舍入并转换为字符串形式的int。这就是我所做的: def __str__(self): return int(round(self.x)) 所以它舍入并转换为int,但不是字符串形式。我试过使用str,但根本不起作用。那么我怎样才能把它转换成字符串形式呢?以下是我的整个要点课程: import math class Error(Exception): def __init__(self, message):

因此,对于我正在编写的point类,我需要编写一个方法,将其舍入并转换为字符串形式的int。这就是我所做的:

def __str__(self):
    return int(round(self.x))
所以它舍入并转换为int,但不是字符串形式。我试过使用str,但根本不起作用。那么我怎样才能把它转换成字符串形式呢?以下是我的整个要点课程:

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)))
现在我还有一个line类,我还没有写完,所以如果这个类看起来很好,那么错误一定在我的line类中

class X:
  def __init__(self):
    self.x = 3.1415
  def __str__(self):
    return str(int(round(self.x)))

x = X()
print x
这会打印
3


这会打印
3

只需将返回的值转换为字符串。在Python数据模型中

object.\uuuu str\uuuuuu(self)
由str(object)和内置函数format()和print()调用,以计算对象的“非正式”或可良好打印的字符串表示形式。返回值必须是字符串对象

\uuuu str\uuu
函数是一个内置函数,必须为对象返回非正式的字符串表示形式。您将返回一个整数表示形式


所以只需将您的
return
更改为
str(int(round(self.x))

只需将您返回的值转换为字符串。在Python数据模型中

object.\uuuu str\uuuuuu(self)
由str(object)和内置函数format()和print()调用,以计算对象的“非正式”或可良好打印的字符串表示形式。返回值必须是字符串对象

\uuuu str\uuu
函数是一个内置函数,必须为对象返回非正式的字符串表示形式。您将返回一个整数表示形式


所以只要把你的
return
改为
str(int(round(self.x)))

他在结尾说他用了str()思想,或者你认为他可能试过
str(round(self.x))
了吗?他在结尾说他用了str()思想,或者你认为他可能试过
str(round(self.x))
?您是如何使用str的?没有先转换成int?这是一个奇怪的错误。错误为TypeError:str返回了非字符串(类型为NoneType)。有没有可能我的str方法是正确的,并且错误来自其他地方?是的,我确实使用了str,但没有先转换为int,它仍然会给出准确的错误。可能只是self。在打印时,x是None,您检查过了吗?另外,您是否定义了
\u repr\u
方法?这可能是导致错误的原因。你是如何使用str的?没有先转换成int?这是一个奇怪的错误。错误为TypeError:str返回了非字符串(类型为NoneType)。有没有可能我的str方法是正确的,并且错误来自其他地方?是的,我确实使用了str,但没有先转换为int,它仍然会给出准确的错误。可能只是self。在打印时,x是None,您检查过了吗?另外,您是否定义了
\u repr\u
方法?这可能是导致错误的原因