是否可以在Python中的函数中定义全局变量

时间:2021-09-14 00:11:57

How do I declare a global variable in a function in Python?

如何在Python中的函数中声明全局变量?

That is, so that it doesn't have to be declared before but can be used outside of the function.

也就是说,它不必在之前声明,但可以在函数之外使用。

2 个解决方案

#1


25  

Yes, but why?

是的,但是为什么?

def a():
    globals()['something'] = 'bob'

#2


5  

def function(arguments):
    global var_name
    var_name = value #must declare global prior to assigning value

This will work in any function, regardless of it is in the same program or not.

这将适用于任何功能,无论它是否在同一程序中。

Here's another way to use it:

这是使用它的另一种方法:

def function():
    num = #code assigning some value to num
    return num

NOTE: Using the return built-in will automatically stop the program (or the function), regardless of whether it is finished or not.

注意:使用内置返回将自动停止程序(或函数),无论它是否完成。

You can use this in a function like this:

你可以在这样的函数中使用它:

if function()==5 #if num==5:
    #other code

This would allow you to use the variable outside of the function. Doesn't necessarily have to be declared global.

这将允许您在函数外部使用变量。不一定要宣布为全球性的。

In addition, to use a variable from one function to another, you can do something like this:

另外,要使用从一个函数到另一个函数的变量,您可以执行以下操作:

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]

This will allow you to use the variable in another function or program without having use a global variable or the return built-in.

这将允许您在不使用全局变量或内置返回的情况下在另一个函数或程序中使用该变量。

#1


25  

Yes, but why?

是的,但是为什么?

def a():
    globals()['something'] = 'bob'

#2


5  

def function(arguments):
    global var_name
    var_name = value #must declare global prior to assigning value

This will work in any function, regardless of it is in the same program or not.

这将适用于任何功能,无论它是否在同一程序中。

Here's another way to use it:

这是使用它的另一种方法:

def function():
    num = #code assigning some value to num
    return num

NOTE: Using the return built-in will automatically stop the program (or the function), regardless of whether it is finished or not.

注意:使用内置返回将自动停止程序(或函数),无论它是否完成。

You can use this in a function like this:

你可以在这样的函数中使用它:

if function()==5 #if num==5:
    #other code

This would allow you to use the variable outside of the function. Doesn't necessarily have to be declared global.

这将允许您在函数外部使用变量。不一定要宣布为全球性的。

In addition, to use a variable from one function to another, you can do something like this:

另外,要使用从一个函数到另一个函数的变量,您可以执行以下操作:

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]

This will allow you to use the variable in another function or program without having use a global variable or the return built-in.

这将允许您在不使用全局变量或内置返回的情况下在另一个函数或程序中使用该变量。