【发布时间】:2016-01-02 20:42:30
【问题描述】:
我一直在努力完成一项任务。我正在调用位于类 ShapeSet 的子类 Triangle 中的 str 方法(我已经突出显示了相关的代码 n-ps)。当我以这种方式调用它时(直接调用它,打印(三角形),工作得很好),我无法获得正确的字符串输出。
当从类 ShapeSet 调用str 方法时:
<method-wrapper 'str' of list object at 0x011E13C8>
直接调用时:
>>>print(triangle):
Type:Triangle, base:3, height:4
我做错了什么?
class Shape(object):
def area(self):
raise AttributeException("Subclasses should override this method.")
class Triangle(Shape):
def __init__(self, base, height):
self.base=base
self.height=height
def area(self):
self.area=(self.base*self.height)/2
return self.area
def __str__(self):
return "Type:{}, base:{}, height:{}".format(self.__class__.__name__, self.base, self.height)
def __eq__(self, other):
return type(other)==Triangle and self.base==other.base and self.height==other.height
class ShapeSet:
def __init__(self):
self.shape_dict={}
def addShape(self, sh):
try:
self.shape_dict[type(sh)].append(sh)
except KeyError:
self.shape_dict[type(sh)]=[sh]
def __iter__(self):
return (self)
def __str__(self):
for value in self.shape_dict.values():
return "{}".format(value.__str__)
shape_set=ShapeSet()
triangle=Triangle(3,4)
shape_set.addShape(triangle)
print (triangle)
【问题讨论】:
-
您能否查看此内容并使用minimal reproducible example 进行更新,更正缩进并明确您获得的输出以及想要的输出。
-
__str__是一个函数,而不是字符串本身,你可以调用__str__(),但这是一个神奇的函数,如果你调用str(value)会调用它,通常你不会直接拨打__str__ -
这个for循环只会看到一个
value,因为你马上return它...for value in self.shape_dict.values(): -
调用
__str__通常是使用内置的str函数完成的,但你真正的问题是没有__repr__方法。