python - 我想要在代码中不使用全局变量的解决方法
问题描述
下面是我的示例,我想要一个不使用函数内部的全局变量的解决方法。
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'
推荐阅读
- r - 在 Windows [rstudio] [r] [windows] 中使用 R(或特别是 R Studio)在指定文件夹中打开文件资源管理器
- c - 为什么在 http 服务器中需要异步?
- dns - 无法连接到在 AWS lightail windows server 2019 上设置的域控制器
- makefile - 配置make在不同目录下为不同系统构建对象
- python - 如何在 Python 上的 3d 数组上应用高斯分布
- php - 如何从数据库中加载 user_email 并将其发布到 Php wp_mail() 函数的 $to 中
- javascript - 下拉列表填充相同的值
- mysql - 在同一台 MySQL 服务器上互连多个数据库
- html - HTML 脚本标签中的 Golang JSON
- windows - 使用 PowerShell 更改音频输出设备