日常使用中的通用功能吗?蟒蛇

时间:2020-11-11 18:19:07

标签: python variables import

我想在另一个变量上工作的函数中有一个变量。 我的代码是这样的:

def my_function(self):
    my_variable = "hello world"
    print(my_variable)

def my_other_function(self):
    if my_variable == "hello world":
        print("pass")

在第二个变量中,它告诉我该变量未定义

有人知道如何使此变量在其他函数中起作用吗?

2 个答案:

答案 0 :(得分:0)

通常我们不会在python函数内部声明全局变量。即使这样,通过使用它们,您也可以实现所需的功能(使变量在两个函数上均起作用)。您的代码如下所示:

def my_function(self):
    global my_variable
    my_variable = "hello world"
    print(my_variable)

def my_other_function(self):
    if my_variable == "hello world":
        print("pass")

不过,我建议您在第一个函数上返回想要的变量,然后在第二个函数上使用它。

在这种情况下,代码如下所示:

def my_function():
    my_variable = "hello world"
    print(my_variable)
    return my_variable

def my_other_function():
    my_variable = my_function()
    if my_variable == "hello world":
        print("pass")

答案 1 :(得分:0)

考虑到您传递给函数的self参数,我假设您正在处理类。在这种情况下,您可以从self对象访问该变量。

class Foo:
    def __init__(self):
        self.my_variable = "foo"

    def my_function(self):
        self.my_variable = "hello world"

    def my_other_function(self):
        if self.my_variable == "hello world":
            print("pass")

my_class = Foo()
my_class.my_function()
my_class.my_other_function()

如果您不使用类,则最好的方法是从函数中返回变量。

def my_function():
    my_variable = "hello world"

    return my_variable

def my_other_function():
    my_var = myfunction()
    if my_var == "hello world":
        print("pass")

您也可以使用全局变量。为此,您应该在函数外部定义一个变量,并告诉python引用该变量。

my_variable = "foo"

def my_function():
    global my_variable

    my_variable = "hello world"
    

def my_other_function():
    global my_variable
    
    if my_variable == "hello world":
        print("pass")

尽管它在脚本编写中非常有用,但不建议使用大代码或应用程序。