gpt4 book ai didi

python - 我想要在代码中不使用全局变量的解决方法

转载 作者:太空宇宙 更新时间:2023-11-04 09:37:44 25 4
gpt4 key购买 nike

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

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 的新手,有人可以帮我解决这个问题吗?

最佳答案

你有

>>> 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'

关于python - 我想要在代码中不使用全局变量的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53058826/

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