繁体   English   中英

在不使用全局的情况下在不同函数中调用变量

[英]Calling a variable in a different function without using global

我试图在另一个函数中定义的函数中使用变量/列表而不使其成为全局函数。

这是我的代码:

def hi():
    hello = [1,2,3]
    print("hello")

def bye(hello):
    print(hello)

hi()
bye(hello)

目前我收到的错误是“bye(hello)”中的“hello”未定义。

我该如何解决这个问题?

您需要从hi方法返回hello。

通过简单的打印,您无法访问hi方法中发生的事情。 在方法内创建的变量仍在该方法的范围内。

有关Python中变量范围的信息:

http://gettingstartedwithpython.blogspot.ca/2012/05/variable-scope.html

你在hi方法中返回hello ,然后,当你打电话给hi ,你应该将结果存储在一个变量中。

所以, hi ,你回来:

def hi():
    hello = [1,2,3]
    return hello

然后,当您调用方法时,将hi的结果存储在变量中:

hi_result = hi()

然后,将该变量传递给bye方法:

bye(hi_result)

如果你不想使用全局变量,你最好的选择就是从hi()调用bye(hello) hi()

def hi():
    hello = [1,2,3]
    print("hello")
    bye(hello)

def bye(hello):
    print(hello)

hi()

你不能声明函数内部全局变量,不会global 。你可以做到这一点

def hi():
    hello = [1,2,3]
    print("hello")
    return hello

def bye(hello):
    print(hello)

hi()
bye(hi())

正如其他人所说的那样,听起来你正试图以不同的方式解决一些更好的事情(参见XY问题

如果hi和bye需要共享不同类型的数据,那么最好使用类。 例如:

class MyGreetings(object):
    hello = [1, 2, 3]

    def hi(self):
        print('hello')

    def bye(self):
        print(self.hello)

您也可以使用全局变量:

global hello

def hi():
    global hello
    hello = [1,2,3]
    print("hello")

def bye():
    print(hello)

或者通过hi返回一个值:

def hi():
    hello = [1,2,3]
    print("hello")
    return hello

def bye():
    hello = hi()
    print(hello)

或者你可以打招呼你好hi函数本身:

def hi():
    hello = [1,2,3]
    print("hello")
    hi.hello = hello


def bye():
    hello = hi.hello
    print(hello)

现在说,完成你所要求的粗略方法是提取hi()的源代码,并在bye()中执行函数体,然后拉出变量hello:

import inspect
from textwrap import dedent


def hi():
    hello = [1,2,3]
    print("hello")

def bye():
    sourcelines = inspect.getsourcelines(hi)[0]
    my_locals = {}
    exec(dedent(''.join(sourcelines[1:])), globals(), my_locals)
    hello = my_locals['hello']
    print(hello)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM