为什么此python方法给出一个错误,提示未定义全局名称? [英] Why does this python method gives an error saying global name not defined?
问题描述
我的Google App Engine项目只有一个代码文件.这个简单的文件只有一个类,并且里面有一些方法.
为什么此python方法给出一个错误,提示未定义全局名称?
Erro NameError:全局名称'gen_groups'未定义
I have a single code file for my Google App Engine project. This simple file has one class, and inside it a few methods.
Why does this python method gives an error saying global name not defined?
Erro 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()
推荐答案
这是一个实例方法,您需要使用self.gen_groups(...)
和self.gen_albums(...)
.
It's an instance method, you need to use self.gen_groups(...)
and self.gen_albums(...)
.
我猜您现在得到的TypeError
是因为您从gen_groups()
中删除了"self"自变量.您需要将其放回原处:
I'm guessing the TypeError
you are getting now is because you removed the 'self' argument from gen_groups()
. You'll need to put it back in:
def get_groups(self, lines):
...
这篇关于为什么此python方法给出一个错误,提示未定义全局名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!