python - 未绑定(bind)本地错误: local variable 'html' referenced before assignment

标签 python html python-3.x python-2.7

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

多库:

关于python - 未绑定(bind)本地错误: local variable 'html' referenced before assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52867542/

相关文章:

python - 将图表添加到 matplotlib 子网格

python - BadFilterError : invalid filter: Only one property per query may have inequality filters (<=, >=, <, >)

python - python 中的 Dev 和 prod 值

python - 在图像上以3:2长宽比绘制矩形

使用 for 循环的 javascript 计数器

python - Pandas:根据与值对应的行数将列中的值替换为 'Other'

python - 如何使用 pytest 测试异常和错误?

javascript - 嵌套 HTML 元素中的冲突事件

c# - 在没有打印对话框的情况下从 C# 中的 Windows 服务打印 html 文档

python-3.x - 包含值超出范围的 ID 的新 DataFrame 列?