你的职能是什么?python

你的职能是什么?python,python,variables,import,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") 在第二个变量中,它告诉我变量是未定义的 有人知道如

函数中有一个变量,我想处理另一个变量。 我的代码是:

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

def my_other_function(self):
    if my_variable == "hello world":
        print("pass")
在第二个变量中,它告诉我变量是未定义的


有人知道如何使这个变量在其他函数中工作吗?

通常我们不会在python中的函数中声明全局变量。即使如此,通过使用它们,您也可以实现您想要的(使变量在两个函数上都工作)。您的代码如下所示:

def my_函数(self):
全局my_变量
my_variable=“你好,世界”
打印(my_变量)
定义我的其他功能(自我):
如果my_变量==“hello world”:
打印(“通行证”)
不过,我建议您在第一个函数中返回所需的变量,然后在第二个函数中使用它

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

def my_函数():
my_variable=“你好,世界”
打印(my_变量)
返回我的_变量
定义my_other_函数():
my_变量=my_函数()
如果my_变量==“hello world”:
打印(“通行证”)

给定传递给函数的
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")

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

要从函数中获取内容,请调用它并检索
返回值