获取TypeError:\uuuu str\uuuuu在Python中返回了非字符串(类型元组)错误

2024-09-30 02:14:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉Python中的类,我正在尝试打印这个方形对象。但是,我一直收到一个错误,它是TypeError:str返回非字符串(type tuple)。告诉我检查第29行和第32行

class Square:
    def __init__(self, lenSide, color):
        self.lenSide = lenSide
        self.color = color
    def __repr__(self):
        return self.lenSide, self.color
    def getSide(self, lenSide):
        return lenSide
    def getArea(self, lenSide):  # return area
        print(lenSide + lenSide)
    def getPerm(self, lenSide):  # return perimeter
        print(self.lenSide*4)
    def setColor(self, color):  # return color
        self.color = color
    def describe(self, color, lenSide):
        print("I am a " + self.color + " square with side" + self.lenSide)
def mySquare():
    newSquare = Square(5, "red")
    print(newSquare)
mySquare()
 

Tags: 对象字符串selfreturndef错误colorprint
3条回答

如注释中所述,repr方法的目标是“以字符串格式返回对象表示形式”。目前,您的实现正在返回元组

您只需将repr修改为以下内容:

def __repr__(self):
    return 'Length:' + str(self.lenSide) + ' ' + 'Color:' + self.color

^{}

Called by the repr() built-in function to compute the “official” string representation of an object. The return value must be a string object.

^{}

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.

因此,必须返回字符串对象,而不是非字符串(在本例中为元组)

def __repr__(self):
    return str(self.lenSide) + ' ' + str(self.color)

从文档中:

Return a string containing a printable representation of an object.

__repr__特殊方法用于返回字符串。返回的不是字符串,而是元组(self.lenSide, self.color)。要将元组转换为字符串,可以使用str()。因此__repr__方法应该返回str((self.lenSide, self.color))(注意额外的parentases以形成元组)

另见: What is the difference between str and repr?

相关问题 更多 >

    热门问题