MrR*_*ROY 39 python function global-variables
如何在Python中的函数中声明全局变量?
也就是说,它不必在之前声明,但可以在函数之外使用.
Jon*_*nts 34
是的,但是为什么?
def a():
globals()['something'] = 'bob'
Run Code Online (Sandbox Code Playgroud)
Rus*_*hal 13
def function(arguments):
global var_name
var_name = value #must declare global prior to assigning value
Run Code Online (Sandbox Code Playgroud)
这将适用于任何功能,无论它是否在同一程序中.
这是使用它的另一种方法:
def function():
num = #code assigning some value to num
return num
Run Code Online (Sandbox Code Playgroud)
注意:使用return内置程序将自动停止程序(或功能),无论程序是否完成.
你可以在这样的函数中使用它:
if function()==5 #if num==5:
#other code
Run Code Online (Sandbox Code Playgroud)
这将允许您在函数外部使用变量.不一定要宣布全球化.
另外,要使用从一个函数到另一个函数的变量,您可以执行以下操作:
import primes as p #my own example of a module I made
p.prevPrimes(10) #generates primes up to n
for i in p.primes_dict:
if p.primes_dict[i]: #dictionary contains only boolean values
print p.primes_dict[i]
Run Code Online (Sandbox Code Playgroud)
这将允许您在不使用全局变量或return内置变量的情况下在另一个函数或程序中使用该变量.
| 归档时间: |
|
| 查看次数: |
56956 次 |
| 最近记录: |