Python 2.7调用compare函数遇类型错误:'Storage'与'int'无法执行减法
解决web.py调用函数时的Storage与int运算错误
嘿,我来帮你搞定这个问题!你遇到的Unsupported operand type(s) for -: 'Storage' and 'int'错误,根源很明确——你把web.py的Storage对象直接传给了compare函数,而不是它需要的数值类型。
错误原因分析
web.py的web.input()返回的是一个Storage对象(本质是支持属性访问的特殊字典),而不是单个数值。你现在把form01、form02、form03这三个Storage对象直接传给compare的参数a、b、c,当函数执行a - 3时,自然会触发类型错误,因为Storage对象和整数无法执行减法运算。
另外还要注意:web表单提交的参数默认是字符串类型,就算你传对了字段,也需要转换成整数才能和3、8这类数值做运算。
解决方案
你需要从每个Storage对象中提取对应的字段值,转换成整数后再传给compare函数。下面是修改后的app02.py代码:
import web import new5 urls = ( '/dyear', 'Index' ) app = web.application(urls, globals()) render = web.template.render('/Users/Administrator/projects/gothonweb/templates/', base="layout01") class Index(object): def GET(self): return render.hello_form01() def POST(self): # 一次性获取所有表单参数,定义默认值 form_data = web.input(a_year=1980, a_month=1, a_day=1) # 提取字段并转换为整数类型 a = int(form_data.a_year) b = int(form_data.a_month) c = int(form_data.a_day) # 传入正确的整数参数调用compare函数 greeting = "Your result from app02 is %s" % (new5.compare(a, b, c)) return render.index(greeting = greeting) if __name__ == "__main__": app.run()
关键修改点
- 合并多次
web.input()调用:你可以在一个web.input()中定义多个参数的默认值,避免创建多个冗余的Storage对象,代码更简洁。 - 类型转换:用
int()把表单传来的字符串参数转换成整数,确保compare函数拿到的是符合要求的数值类型。 - 传递正确参数:不再传递整个Storage对象,而是提取后的具体数值给
compare函数的a、b、c。
如果你坚持要分开调用web.input(),也可以这样修改:
def POST(self): form01 = web.input(a_year=1980) form02 = web.input(a_month=1) form03 = web.input(a_day=1) # 提取并转换每个字段的值 a = int(form01.a_year) b = int(form02.a_month) c = int(form03.a_day) greeting = "Your result from app02 is %s" % (new5.compare(a, b, c)) return render.index(greeting = greeting)
这样修改后,compare函数就能正常执行数值运算和逻辑判断了。
内容的提问来源于stack exchange,提问作者EggShell
相关产品推荐
相关产品推荐

