我使用全局变量,但我读到它们不是一个好的实践或 pythonic。我经常使用的函数会给出许多我需要在主函数中使用的是/否变量。例如,如何在不使用全局变量的情况下编写以下代码?
def secondary_function():
global alfa_is_higher_than_12
global beta_is_higher_than_12
alfa = 12
beta = 5
if alfa > 10:
alfa_is_higher_than_12 = "yes"
else:
alfa_is_higher_than_12 = "no"
if beta > 10:
beta_is_higher_than_12 = "yes"
else:
beta_is_higher_than_12 = "no"
def main_function():
global alfa_is_higher_than_12
global beta_is_higher_than_12
secondary_function()
if alfa_is_higher_than_12=="yes":
print("alfa is higher than 12")
else:
print("alfa isn't higher than 12")
if beta_is_higher_than_12=="yes":
print("beta is higher than 12")
else:
print("beta isn't higher thant 12")
main_function()
原文由 Carl 发布,翻译遵循 CC BY-SA 4.0 许可协议
有人可能会问为什么你必须这样构造你的代码,但假设你有你的理由,你可以只从你的辅助函数返回值: