小编Car*_*arl的帖子

如何避免使用全局变量?

我使用全局变量,但我读过它们不是一个好的做法或 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()
Run Code Online (Sandbox Code Playgroud)

python if-statement function global-variables python-3.x

4
推荐指数
2
解决办法
6979
查看次数