变量不适用于子功能 [英] Variable not available to sub-function

查看:77
本文介绍了变量不适用于子功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此脚本在 main()中定义了一个变量,但是该变量对 main()中运行的 func()不可用.代码>.为什么会这样?

This script defines a variable inside main(), but the variable isn't available to func(), which runs inside main(). Why is that?

#!/usr/bin/env python3
# vars_in_func.py
# Test script for variables within a function.

def func():
  print(greeting)

def main():
  greeting = "Hello world"
  func()

main()

错误:

Traceback (most recent call last):
  File "./vars_in_func.py", line 11, in <module>
    main()
  File "./vars_in_func.py", line 9, in main
    func()
  File "./vars_in_func.py", line 5, in func
    print(greeting)
NameError: name 'greeting' is not defined

如果我将脚本转换为Python2,则错误是相同的,除了它说的是 global name 而不是 name .

If I convert the script to Python2, the error is the same, except it says global name instead of name.

我认为我只是缺少一个关键概念.在学习了Bash之后,我才开始学习Python.

I assume I'm just missing a key concept. I just started learning Python after learning Bash.

编辑:阅读答案后,我意识到了我的错误:我仍在考虑Bash,即函数与调用程序在相同的shell中运行(具有相同的变量),或调用方的子外壳(继承的变量).

Edit: After reading the answers, I realized my mistake: I'm still thinking in terms of Bash, where functions either run in the same shell as the caller (with the same variables), or a subshell of the caller (inherited variables).

推荐答案

greeting = None

def func():
    print(greeting)

def main():
   global greeting
   greeting = "Hello world"
   func()

main()

在您的解决方案中,在main函数中定义的问候语是一个局部变量,不能在main函数外部访问.这就是它给你错误的原因

In your solution, greeting defined in main function is a local variable and can't be accessed outside main function. that is the reason it was giving you errors

这篇关于变量不适用于子功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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