[英]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.