![](/img/trans.png)
[英]How to use variable of one function to another function without declaring global variable in this case?
[英]How to call variable from another function by declaring global in python?
功能 1
def num1():
global h
h=7
功能 2
def num2():
print(h)
當我稱之為 function 時:
num2()
在這里,它應該打印在func 1
中全局聲明的h
的值。 但它給NameError
為什么? 有人回答我嗎lz..
要通過num2()
訪問全局變量h
,請確保在調用num2()
num1()
)
定義num1
實際上並沒有定義h
。 num1
的定義只是說,當您調用num1
時,它將分配給全局名稱h
。 如果當時h
不存在,它將被創建。 但是定義num1
不足以創建h
。
您需要確保h
在調用num2
之前存在。 您可以通過自己分配給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.