我不熟悉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()
如注释中所述,repr方法的目标是“以字符串格式返回对象表示形式”。目前,您的实现正在返回元组
您只需将repr修改为以下内容:
^{}
^{}
因此,必须返回字符串对象,而不是非字符串(在本例中为元组)
从文档中:
__repr__
特殊方法用于返回字符串。返回的不是字符串,而是元组(self.lenSide, self.color)
。要将元组转换为字符串,可以使用str()
。因此__repr__
方法应该返回str((self.lenSide, self.color))
(注意额外的parentases以形成元组)另见: What is the difference between str and repr?
相关问题 更多 >
编程相关推荐