Python UnboundLocalError: 局部变量...在赋值前被引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4048745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UnboundLocalError: local variable ... referenced before assignment
提问by Zeynel
I get an UnboundLocalErrorbecause I use a template value inside an if statement which is not executed. What is the standard way to handle this situation?
我得到一个,UnboundLocalError因为我在未执行的 if 语句中使用了模板值。处理这种情况的标准方法是什么?
class Test(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
greeting = ('Hello, ' + user.nickname())
else:
self.redirect(users.create_login_url(self.request.uri))
...
template_values = {"greeting": greeting,
}
Error:
错误:
UnboundLocalError: local variable 'greeting' referenced before assignment
采纳答案by fabrizioM
Just Switch:
只需切换:
class Test(webapp.RequestHandler):
def err_user_not_found(self):
self.redirect(users.create_login_url(self.request.uri))
def get(self):
user = users.get_current_user()
# error path
if not user:
self.err_user_not_found()
return
# happy path
greeting = ('Hello, ' + user.nickname())
...
template_values = {"greeting": greeting,}
回答by Martin v. L?wis
I guess I need to explain the problem first: in creating template_values, you use a greeting variable. This variable will not be set if there is no user.
我想我需要先解释一下这个问题:在创建 template_values 时,你使用了一个 greeting 变量。如果没有用户,则不会设置此变量。
There isn't a standard way to handle this situation. Common approaches are:
没有处理这种情况的标准方法。常用的方法有:
1. make sure that the variable is initialized in every code path (in your case: including the else case)
2. initialize the variable to some reasonable default value at the beginning
3. return from the function in the code paths which cannot provide a value for the variable.
Like Daniel, I suspect that after the redirect call, you are not supposed to produce any output, anyway, so the corrected code might read
像丹尼尔一样,我怀疑在重定向调用之后,无论如何你都不应该产生任何输出,所以更正后的代码可能会读取
class Test(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
greeting = ('Hello, ' + user.nickname())
else:
self.redirect(users.create_login_url(self.request.uri))
return
...
template_values = {"greeting": greeting,
}

