【问题标题】:Python: How to use named variables from one function in other functionsPython:如何在其他函数中使用来自一个函数的命名变量
【发布时间】:2013-11-25 14:54:53
【问题描述】:

我是一名新手程序员,正在尝试使用 Python 3.3.2 编写一个程序,该程序具有一个 main() 函数,该函数调用 function1(),然后循环 function2()function3()

我的代码一般是这样的:

def function1():
    print("hello")

def function2():
    name = input("Enter name: ")

def function3():
    print(name)

def main():
    function1()
    while True:
        funtion2()
        function3()
        if name == "":
            break

main()

目前,我在运行程序并输入名称时收到以下错误:

NameError: global name 'name' is not defined

我了解这是因为 name 仅在 function2() 中定义。如何使name 被定义为“全局名称”,或者以某种方式能够在function3()main() 中使用它。

提前致谢。

【问题讨论】:

    标签: python function python-3.x global-variables


    【解决方案1】:

    不要尝试将其定义为全局变量,而是将其返回:

    def function2():
        name = input("Enter name: ")
        return name
    
    def function3():
        print(function2())
    

    如果你想使用在函数中定义的变量在所有函数中都可用,那么使用一个类:

    class A(object):
    
       def function1(self):
           print("hello")
    
       def function2(self):
           self.name = input("Enter name: ")
    
       def function3():
           print(self.name)
    
       def main(self):  
           self.function1()
           while True:
              funtion2()
              function3()
              if not self.name:
                  break
    
    A().main()
    

    【讨论】:

    • 我试过了,但现在它返回了这个错误:Traceback (most recent call last): File "I:\School\ITEC 1150-02\Address book group assignment\TEAMLAB2.py", line 43, in <module> A().main() File "I:\School\ITEC 1150-02\Address book group assignment\TEAMLAB2.py", line 37, in main function2() NameError: global name 'function2()' is not defined
    • 没关系,我让它工作了;使用self.function2() 而不仅仅是function2()。非常感谢!
    【解决方案2】:

    在函数外部定义变量,然后首先在内部使用global 关键字将其声明为全局变量。虽然,这几乎总是一个坏主意,因为您最终会使用全局状态创建所有可怕的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-25
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 2021-11-13
      相关资源
      最近更新 更多