首页 > 解决方案 > 我想要在代码中不使用全局变量的解决方法

问题描述

下面是我的示例,我想要一个不使用函数内部的全局变量的解决方法。

Legend = '''
<style>
table {
    font-family: Times New Roman, sans-serif;
    border-collapse: collapse;
    width: 100%;
}
td, th {
    border: 1px solid #000000;
    text-align: center;
    height: 20px;
    overflow: hidden;
    padding: 2px;
}
tr:nth-child(even) {
    background-color: #ffffff;
}
</style> '''
for i in ts:
    Legend+= '<th>' + i + '</th>'
Legend += '''</tr>'''

def get_data_legend(value,name,sym=None):
    global Legend
    L1 = []
    for i in value:
       L1.append('{:,.0f}'.format(i))
    Legend += '''<tr><th>'''+name+'''</th>'''
    for i in gt:
        if sym is not None:
             Legend+= '<td>' + sym + str(i)  + '</td>'
        else:
             Legend += '<td>' + ' ' + str(i)  + '</td>'
    Legend += '''</tr>'''

get_data_legend(update_datapoints,'Update metrics')
get_bus_metrics(update_address,'Update address')
Legend += '''</tr></table><br><br>'''

我在函数内部使用了不好用或最差使用的全局变量。我正在寻找一种解决方法,这样我就不需要在函数内使用全局变量。我是python的新手,有人可以帮我解决这个问题。

标签: pythonfunctionglobal-variables

解决方案


你有

>>> something = 'something'
>>> def bad():
...:    global something
...:    something += ' bad'
...:
>>> bad()
>>> something
>>> 'something bad'

你应该有

>>> def good(something):
...:    something += ' good'
...:    return something
...:
>>> something = good('something')
>>> something
>>> 'something good'

推荐阅读