简体   繁体   English

如何通过在 python 中声明全局来从另一个 function 调用变量?

[英]How to call variable from another function by declaring global in python?

func 1功能 1

def num1():
    global h
    h=7

func 2功能 2

def num2():  
     print(h)

When I call this function:当我称之为 function 时:

num2()

Here, it should print the value of h which is globally declared in func 1 .在这里,它应该打印在func 1中全局声明的h的值。 But it is giving NameError why??但它给NameError为什么? Anyone answer me plz..有人回答我吗lz..

to access the global variable h through num2() make sure to call num1() before calling num2()要通过num2()访问全局变量h ,请确保在调用num2() num1() )

Defining num1 doesn't actually define h .定义num1实际上并没有定义h The definition of num1 just says that, when you call num1 , it will assign to the global name h . num1的定义只是说,当您调用num1时,它将分配给全局名称h If h doesn't exist at that time, it will be created.如果当时h不存在,它将被创建。 But defining num1 isn't sufficient to create h .但是定义num1不足以创建h

You need to ensure that h exists before num2 is called.您需要确保h在调用num2之前存在。 You can do that by assigning to h yourself, or calling num1 .您可以通过自己分配给h或调用num1来做到这一点。

>>> num2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in num2
NameError: name 'h' is not defined
>>> h = 3
>>> num2()
3
>>> del h
>>> num2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in num2
NameError: name 'h' is not defined
>>> num1()
>>> num2()
7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM