相关疑难解决方法(0)

在不使用"global"的情况下访问函数外部的函数变量

我试图在Python中访问函数外部的本地函数变量.所以,例如,

bye = ''
def hi():
    global bye
    something
    something
    bye = 5
    sigh = 10

hi()
print bye
Run Code Online (Sandbox Code Playgroud)

以上工作正常.由于我想知道我是否可以byehi()不使用的情况下访问外部global bye,我试过:

def hi():
    something
    something
    bye = 5 
    sigh = 10
    return

hi()
x = hi()
print x.bye 
Run Code Online (Sandbox Code Playgroud)

以上给出AttributeError: 'NoneType' object has no attribute 'bye'.

然后,我试过:

def hi():
    something
    something
    bye = 5
    sigh = 10
    return bye 
hi()
x = hi()
print x.bye
Run Code Online (Sandbox Code Playgroud)

这次它甚至没有出错.

那么,有没有办法在不使用全局变量的情况下访问函数(bye)之外的本地函数变量()hi()而不打印变量sigh?(问题编辑后包括 …

python local-variables

32
推荐指数
2
解决办法
15万
查看次数

标签 统计

local-variables ×1

python ×1