我是Python的新手,我真的很想知道为什么会出现这个错误。
在尝试执行第二个findLargest
循环时,我的for
函数中会发生这种情况。问题是第二个for
循环与第一个循环基本相同,但出于某种原因,当我尝试调用(class)method
时出现错误。怎么会这样?我不允许在同一个函数中为同一个迭代创建2个for循环吗?
shapeArea=shape.area()
投掷:
TypeError: 'float' object is not callable
findlargest()
的目标是循环遍历类的集合两次,首先是为了找到最大的value(Area)
,而第二个尝试查找是否有其他值相等。
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 "{} with base {} and 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_list = []
def addShape(self, sh):
if sh not in self.shape_list:
self.shape_list.append(sh)
else:
print ("{} is already existing".format(sh.__str__()))
def __iter__(self):
return (self.shape_list)
def __str__(self):
s = ''
for shape in self.__iter__():
s+= shape.__str__() + "\n"
return s
ss = ShapeSet()
ss.addShape(Triangle(1.2,2.5))
ss.addShape(Triangle(1.4,2.5))
ss.addShape(Triangle(1.3,2.5))
ss.addShape(Triangle(1.5,2.5))
def findLargest(shapes):
maxs = None
maxA = 0.0
for shape in shapes.__iter__():
shapeArea = shape.area()
if shapeArea > maxA or maxs == None:
maxs = shape
maxA = shapeArea
maxTuple = (maxs)
for shape in shapes.__iter__():
shapeArea = shape.area()
答案 0 :(得分:1)
有了这个:
def area(self):
self.area=(self.base*self.height)/2
return self.area
输入方法,然后通过为其引用指定其他名称立即对其进行掩码。从那时起,self.area
引用该数字,您无法再访问该方法。幸运的是,修复很容易:根本不保存引用。
def area(self):
return self.base * self.height / 2
Python不会分隔函数/方法对象和其他对象的名称。为您要保留的任何对象使用唯一的引用名称。
答案 1 :(得分:0)
我认为你的问题在这里:
class Triangle(Shape):
def __init__(self, base, height):
self.base=base
self.height=height
def area(self):
self.area=(self.base*self.height)/2 ###################### HERE
return self.area
如果你有
shape = Triangle(1.5,2.5)
shape.area() # returns float assigned at "HERE" to shape.area
shape.area() # try to call that float assigned in previous step at "HERE"