python中将main函数写成接口后main函数中的参数不能传递问题

 

 

在main函数这种定义了一些参数,但是将main函数改写成普通函数供其他py文件调用的时候,我们发现原来的参数在ide中变成了灰色,而且不能顺利的传递给普通函数调用的函数。

在python的main函数中的变量默认为全局变量,而其他的def函数中的变量则默认为局部变量

在普通的def函数A里面,在调用其他函数B的时候,要一起把B函数需要的参数传递进去:

看例子:

gl_count = 500  # 全局变量


def my_fun_local():
    gl_count = 0  # 这个count是局部变量,外面的 全局变量与其虽然同名但是无关
    print("my_fun_local ", gl_count)  # 打印局部变量


def my_fun_global():
    global gl_count
    print("my_fun_global ", gl_count)  # 打印全局变量
    gl_count = 5  # 这个count是全局变量,在函数内部进行的修改 会影响到函数外部
    print("my_fun_global ", gl_count)  # 打印全局变量


def main():
    my_fun_local()
    print("main ", gl_count)  # 打印的是全局变量
    my_fun_global()
    print("main ", gl_count)  # 打印的是全局变量


if __name__ == '__main__':
    main()

最方便的解决方法就是把变量提到函数外作为全局变量或者加上global

python中将main函数写成接口后main函数中的参数不能传递问题

 

相关文章:

  • 2022-12-23
  • 2021-06-20
  • 2021-05-17
  • 2021-07-05
  • 2023-03-13
  • 2021-10-09
  • 2022-12-23
猜你喜欢
  • 2021-09-14
  • 2022-02-10
  • 2022-01-08
  • 2021-09-20
  • 2022-03-01
  • 2021-05-12
相关资源
相似解决方案