如何避免使用全局变量? [英] How to avoid using global variables?

查看:169
本文介绍了如何避免使用全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了全局变量,但是我读过它们不是一个好习惯,也不是pythonic.因此,我经常使用一些函数,这些函数会给出在主函数中需要使用的许多yes/no变量.例如,如何在不使用全局变量的情况下编写以下代码?

I use global variables but I've read that they aren't a good practice or pythonic. I often use functions that give as a result many yes/no variables that I need to use in the main function. For example, how can I write the following code without using global variables?

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

推荐答案

一个人可能会问,为什么有必要构造这样的代码,但是如果您有自己的理由,则可以从辅助函数返回值:

One could ask what reasons you might have to structure your code like this, but assuming you have your reasons, you could just return the values from your secondary 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")

这篇关于如何避免使用全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆