gpt4 book ai didi

在使用相同名称定义局部变量之前,python 无法访问非局部变量

转载 作者:太空狗 更新时间:2023-10-29 21:32:13 25 4
gpt4 key购买 nike

<分区>

我以前使用过装饰器,所以我很惊讶地发现我的代码中有一个错误:

def make_handler(name, panels):
def get(self):
admin = True
keys = [ndb.Key('Panel', panel) for panel in panels]
panels = zip(ndb.get_multi(keys), panels)
panels = [(panel.panel_html if panel else get_default_content(panel_id), panel_id) for panel, panel_id in panels]
templates = {'panels': panels, 'admin': admin}
self.render_template('panel_page.html', **templates)
return type(name, (BaseHandler,), {'get': get})

产生的错误是:

Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\lib\webapp2\webapp2.py", line 1536, in __call__
rv = self.handle_exception(request, response, e)
File "C:\Program Files\Google\google_appengine\lib\webapp2\webapp2.py", line 1530, in __call__
rv = self.router.dispatch(request, response)
File "C:\Program Files\Google\google_appengine\lib\webapp2\webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "C:\Program Files\Google\google_appengine\lib\webapp2\webapp2.py", line 1102, in __call__
return handler.dispatch()
File "C:\Program Files\Google\google_appengine\lib\webapp2\webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "C:\Program Files\Google\google_appengine\lib\webapp2\webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "C:\Users\Robert\PycharmProjects\balmoral_doctors\main.py", line 35, in get
keys = [ndb.Key('Panel', panel) for panel in panels]
UnboundLocalError: local variable 'panels' referenced before assignment

我的解决方法是在第一次使用后将 panel 更改为 panel2:

def make_handler(name, panels):
def get(self):
admin = True
keys = [ndb.Key('Panel', panel) for panel in panels]
panels2 = zip(ndb.get_multi(keys), panels)
panels2 = [(panel.panel_html if panel else get_default_content(panel_id), panel_id) for panel, panel_id in panels2]
templates = {'panels': panels2, 'admin': admin}
self.render_template('panel_page.html', **templates)
return type(name, (BaseHandler,), {'get': get})

这是我的理解:panels = zip(...) 意味着 panels 是一个局部变量,因此该函数不会在外部范围内查找面板。

这是在 get() 函数运行之前完成的,而不是中途完成的?

我以为它会先从外部函数中获取面板,然后当面板在内部函数中定义之后,它会从那时起使用新的本地面板变量。

我走在正确的轨道上吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com