【问题标题】:Unsupported operand type(s) for -: 'Storage' and 'int'- 不支持的操作数类型:“Storage”和“int”
【发布时间】:2018-11-08 02:26:51
【问题描述】:

我正在学习 Python 2.7 并尝试在名为 new5.py 的模块中编写一个函数,如下所示:

def compare(a,b,c):
    if a - 3 == 8:
        return "I like a!"
    elif b == c:
        return "I like c!"
    else:
        return "I like b!"

当我尝试调用名为 app02.py 的模块中的函数时,该模块在 qustion 末尾显示详细代码,我被告知如下所示,在屏幕上显示如下拍摄:

我猜问题出在a,但是我应该怎么做才能使用这个功能呢?谢谢!

------以下是从web.py 0.3根植的模块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):
        form01 = web.input(a_year=1980)
        form02 = web.input(a_month=01)
        form03 = web.input(a_day=01)

        greeting = "Your result from app02 is %s" % (new5.compare(form01, form02, form03))
        return render.index(greeting = greeting)

if __name__ == "__main__":
    app.run()

【问题讨论】:

  • 你是怎么调用函数的?
  • 调用函数时传递给函数的a、b、c的值是多少?
  • 你在哪一行得到错误?请给我们完整的错误信息。
  • 非常感谢,我在问题的编辑中添加了更多详细信息,包括添加错误消息屏幕截图。请给我一个建议。 @Flaming_Dorito
  • @supra28,谢谢你!我详细介绍了如何在新编辑中调用该函数。请指教。

标签: python python-2.7 typeerror web.py


【解决方案1】:

您应该访问 form01 中的 a_year、form02 中的 a_month 和 form03 中的 a_day 对象,例如 form01.a_yearform2.a_monthform3.a_day,而不是将整个 Storage 对象传递给 compare() 所以你的函数调用应该看起来像

greeting = "Your result from app02 is %s" % (new5.compare(form01.a_year, form02.a_month, form03.a_day))

另外,请注意docs

请注意,web.input() 值将是字符串,即使有 传递给它的数字。

所以你需要像这样将你的 web.input 从字符串类型转换为所需的类型(这里是 int)

if int(a) - 3 == 8:

【讨论】:

  • 非常感谢! @Priya,我用你的建议解决了这个问题。
猜你喜欢
  • 2015-01-17
  • 2016-09-07
  • 2022-01-03
  • 2018-12-13
  • 2018-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多