如何在一个Python函数中访问另一个函数中的变量

3
我编写了几个函数来计算样本响应的NPS和误差率。
我不想从第一个函数返回结果,然后将它传递到另一个函数中以便能够使用它们。
因此,我想创建全局变量,这些变量可以在创建它的函数之外使用,以便在其他函数中使用它们而无需传递它们。
但是似乎会抛出错误。有什么办法可以实现这一点吗?我不想使用类并将这些变量作为类变量。
def nps_score(responses): 
    """Function to get the NPS score from the 
     Survey responses 

    """
    global sample_size = len(responses)
    global promoters_proportion = sum([1 for x in responses if x >=9])/sample_size
    global detractors_proprotion= sum([1 for x in responses if x<=6])/sample_size

    global sample_NPS= promoters_proportion - detractors_proportion

    print("Sample Net Promoter Score(NPS) is {} or {}%".format(sample_NPS,sample_NPS*100))



def moe():
    """ Calculate the margin of error
    of the sample NPS 

    """

    # variance/standard deviation of the sample NPS using 
    # Discrete random variable variance calculation

    sample_variance= (1-sample_NPS)^2*promoters_proportion + (-1-sample_NPS)^2*detractors_proportion

    sample_sd= sqrt(sample_variance)

    # Standard Error of sample distribution

    standard_error= sample_sd/sqrt(sample_size)

    #Marging of Error (MOE) for 95% Confidence level
    moe= 1.96* standard_error

    print("Margin of Error for sample_NPS of {}% for 95% Confidence Level is: {}%".format(sample_NPS*100,moe*100))

你现在还不知道返回值吗?你至少已经写了5年的Python了。 - user2357112
3
等等,再读一遍,你说你不想返回这些值。为什么?相比全局变量而言,使用 return 更不容易引起问题。 - user2357112
我不想返回值,然后将其保存到另一个变量中,只为了传递给更多的函数。 - Baktaawar
你也可以使用函数属性,例如在定义了 nps_score 函数之后,你可以添加 nps_score.sample_size = 0 ,然后你可以在 nps_score 内外都用 nps_score.sample_size 调用这个值。不过并不是说你应该这么做。 - Headcrab
我不想返回值,然后将其保存到另一个变量中,只是为了传递给另一个函数。如果它将立即传递给另一个函数,并且对其他任何事情都没有用处,则不需要中间变量:another_function(first_function())。但是,一般来说,不清楚为什么您不想执行这些赋值操作。任何其他方法都至少需要同样的工作量。全局变量(如果它们不是常量)会使程序逻辑更难理解。 - Karl Knechtel
1个回答

8

您需要将变量声明为全局变量,然后使用它。像这样:

def add_to_outside():
    global outside #say that it is global
    outside = 1 #now create it!

def see_it():
    global outside #say that it is global
    print(outside)

##As shown:
add_to_outside()
see_it()
#output: 1

在函数开头加上关键字global,可以使该函数内所有同名变量引用全局值。不要在同一语句中声明变量为全局变量并更改它。

此外,只需在函数开头放置global关键字。它不需要紧挨着对变量的更改,并且只需要使用一次。

要声明多个变量为全局变量,请按以下方式进行:

global var1, var2, var3 #etc.

这是在函数外声明变量。我想要在另一个函数中使用在一个函数内声明的变量。 - Baktaawar
“global”是唯一的方法,而不使用“return”。只需让一个函数调用引用另一个函数更改的全局变量即可。如果您想要“在函数中创建”的行为,只需不在开头创建变量,例如,不要使用“outside = 0”行。我已经更新了我的示例来展示这一点。 - Eb946207
1
好的,明白了。问题是不能在同一语句中更改变量。但是当它已经在上层函数中声明时,在see_it()函数中是否仍需要将其声明为全局变量? - Baktaawar
@Baktaawar,如果您想要改变数值,那么是的。有些例外情况(比如您只需要读取数值),但最好总是这样做,否则可能会导致不必要的行为。 - Eb946207

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接