TypeError: 'classobj'对象没有'__getitem__'属性

1 投票
3 回答
2242 浏览
提问于 2025-04-18 15:35

我刚开始学习Python,完全不知道该怎么解决这个问题。请帮帮我。

错误信息:

Traceback (most recent call last):
  File "C:\Users\Priscilla\Desktop\CMPT Assn #3\page.py", line 17, in <module>
    print "<p>Customer Name:", form["custName"].value, "</p>"
TypeError: 'classobj' object has no attribute '__getitem__'

Python脚本:

import cgi
form = cgi.FieldStorage

# print HTTP/HTML header stuff
print """Content-type: text/html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head>
<title>Order Form</title>
</head><body>
"""

# print HTML body using form data
print "<h1>Kintoro Japanese Bar &amp; Restaurant</h1>"
print "<h2>Customer Reciept</h2>"
print "<p>Customer Name:", form["custName"].value, "</p>"
print "<p>Customer Email Address:", form["custEmail"].value, "</p>"
print "<h2>Customer Address:</h2>"
print "<p>Street:", form["custAdd"].value, "</p>"
print "<p>City:", form["custCity"].value, "</p>"
print "<p>Province:", form["custProv"].value, "</p>"
print "<p>Postal Code:", form["custPostal"].value, "</p>"
print "<h2>Payment Information:</h2>"
print "<p>Card Type:", form["type1"].value, "</p>"
print "<p>Card Number: XXXX-XXXX-XXXX-", form["four4"].value, "</p>"
print "<p>Expiry Date:", form["expDate"].value, "</p>"

3 个回答

0

在Python中,当你使用 [] 这个符号时,其实是在调用对象的 __getitem__(key) 方法。看起来在你的情况下,这个方法并没有在 form 所属的类中定义。

要解决这个问题,你需要在相关的类中定义这个方法,并告诉它应该怎么工作。

想了解更多信息,可以查看 文档

1

你不需要直接创建一个 FieldStorage 的实例。

你应该这样做:form = cgi.FieldStorage。这样做会让 form 变成 cgi.FieldStorage 这个类本身。这个类并不知道你当前的请求是什么。

你想要的其实是:form = cgi.FieldStorage()。这样做会创建一个新的实例,这个实例和你当前的请求是关联在一起的。

2

form = cgi.FieldStorage 这行代码是把 FieldStorage 这个类本身赋值给了 form。其实你应该把 FieldStorage 的一个实例(也就是一个具体的对象)赋值给 form,而不是类本身。

form = cgi.FieldStorage()

撰写回答