gpt4 book ai didi

python - 如何避免使用全局变量?

转载 作者:行者123 更新时间:2023-12-03 18:28:38 27 4
gpt4 key购买 nike

我使用全局变量,但我读过它们不是一个好的做法或 pythonic。我经常使用的函数会给出许多我需要在主函数中使用的 yes/no 变量。例如,如何在不使用全局变量的情况下编写以下代码?

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()

最佳答案

有人可能会问有什么原因可能需要像这样构造代码,但假设您有自己的原因,您可以只从辅助函数中返回值:

def secondary_function():

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"

return alfa_is_higher_than_12, beta_is_higher_than_12


def main_function():

alfa_is_higher_than_12, 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")

关于python - 如何避免使用全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59330578/

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