为什么这个Python方法会出现“全局名称未定义”的错误?
我有一个Google App Engine项目,只有一个代码文件。这个简单的文件里有一个类,里面有几个方法。
为什么这个Python方法会报错,提示说全局名称没有定义?
错误信息是:NameError: global name 'gen_groups' is not defined
import wsgiref.handlers
from google.appengine.ext import webapp
from django.utils import simplejson
class MainHandler(webapp.RequestHandler):
def gen_groups(self, lines):
""" Returns contiguous groups of lines in a file """
group = []
for line in lines:
line = line.strip()
if not line and group:
yield group
group = []
elif line:
group.append(line)
def gen_albums(self, groups):
""" Given groups of lines in an album file, returns albums """
for group in groups:
title = group.pop(0)
songinfo = zip(*[iter(group)]*2)
songs = [dict(title=title,url=url) for title,url in songinfo]
album = dict(title=title, songs=songs)
yield album
def get(self):
input = open('links.txt')
groups = gen_groups(input)
albums = gen_albums(groups)
print simplejson.dumps(list(albums))
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
3 个回答
1
你需要这样使用:
self.gen_groups(input)
在Python中,没有隐含的“self”。
1
你需要明确地用一个实例来调用它:
groups = self.gen_groups(input)
同样,对于你在里面做的其他一些调用,比如 gen_album
也是如此。
另外,可以查看 了解何时使用 self 和 __init__
来获取更多信息。
5
这是一个实例方法,你需要用 self.gen_groups(...)
和 self.gen_albums(...)
来调用它。
补充说明:我猜现在你遇到的 TypeError
错误是因为你把 gen_groups()
方法里的 'self' 参数去掉了。你需要把它加回来:
def get_groups(self, lines):
...