html += '''
<table style="width:100%">
<tr align="center">
<th style="width:10%">Metrics</th>
'''
def get_bus_metrics (met,name):
for i in met:
html += '<th>' + str(i) + '</th>'
html += '''</tr>'''
html += '''<tr><th>''' + name +'''</th>'''
get_bus_metrics (g1,'R')
UnboundLocalError: local variable 'html' referenced before assignment
我收到此错误。 有人可以建议我这里缺少什么,为什么我会收到上述错误。
最佳答案
如果之前未使用该变量,则修复 +=
并将其提供给函数:
# fix here - no += unless you decleared html as some string beforehand
html = '''
<table style="width:100%">
<tr align="center">
<th style="width:10%">Metrics</th>
'''
# fix here - else not known
def get_bus_metrics (met,name,html):
for i in met:
html += '<th>' + str(i) + '</th>'
html += '''</tr>'''
html += '''<tr><th>''' + name +'''</th>'''
return html
html = get_bus_metrics (range(1,5),'R',html) # provide as parameter: cleaner
print(html) #
输出:
<table style="width:100%">
<tr align="center">
<th style="width:10%">Metrics</th>
<th>1</th><th>2</th><th>3</th><th>4</th></tr><tr><th>R</th>
或者(不太可取)将其声明为全局:
def get_bus_metrics (met,name,html):
# don't use globals, they are _evil_ - if you need to _modify_ smth
# from global scope, you need to announce this in the function
# reading works without if decleard earlier then the function,
# changing it needs this line:
global html
for i in met:
html += '<th>' + str(i) + '</th>'
html += '''</tr>'''
html += '''<tr><th>''' + name +'''</th>'''
提示 1:
使用 str.format() 更好的字符串格式或f-strings / PEP-0498 / Literal String Interpolation
提示 2:
在循环中添加字符串是一种浪费——它会构造大量被丢弃的中间字符串。使用列表代替
def get_bus_metrics (met,name,html):
t = []
for i in met:
t.append('<th>{}</th>'.format(i)) # using format(..)
t.append(f'</tr><tr><th>{name}</th>') # using string interpol
return html+''.join(t) # faster, less wasted intermediate strings
多库:
- str.format() - 适用于 2.7
- PEP-0498 string interpol适用于 3.6+
- Short Description of the Scoping Rules?如果您想了解范围界定
关于python - 未绑定(bind)本地错误: local variable 'html' referenced before assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52867542/