Python自定义函数中max函数失效报错TypeError: 'bool'对象不可调用
Python代码报错原因及修复
报错原因
你的代码触发错误的核心原因是变量名和Python内置函数名冲突:
- 代码中
max=result[2]这一行,把Python内置的max()求最大值函数的名称,重新赋值为了布尔类型的变量(从你后续的if max==True判断逻辑可以看出,result[2]的值是布尔类型)。 - 后续执行
cost=max(result[0])时,Python会将max识别为你赋值的布尔值,而布尔对象无法被调用执行,因此抛出TypeError: 'bool' object is not callable错误。
修复方法
将自定义的布尔变量修改为不和Python内置函数重名的名称即可,参考修改后的代码:
def printDays(result): days=result[1] # 修改变量名,避免覆盖内置max函数 need_max = result[2] budget=result[3] if need_max: cost=max(result[0]) else: cost=min(result[0]) template="You can spend $ {} in {} days with a $ {} limit" print(template.format(cost,days,budget))
内容的提问来源于stack exchange,提问作者gerdtf
相关产品推荐
相关产品推荐

