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

ask*_*nce 32 python local-variables

我试图在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?(问题编辑后包括sigh@hcwhsa的评论如下.

mar*_*eau 74

您可以沿着这条线做一些事情(当我测试它/它们时,它在Python v2.7.15和v3.7.1中都有效):

def hi():
    # other code...
    hi.bye = 42  # Create function attribute.
    sigh = 10

hi()
print(hi.bye)  # -> 42
Run Code Online (Sandbox Code Playgroud)

函数是Python中的对象,可以为其分配任意属性.

如果您经常要做这种事情,可以通过创建一个函数装饰器来实现更通用的东西,该函数装饰器this为每个对装饰函数的调用添加一个参数.

这个额外的参数将为函数提供一种引用自身的方法,而不需要将它显式地嵌入(硬编码)到它们的定义中,并且类似于类方法自动接收的实例参数作为它们通常命名的第一个参数self- 我选择了不同的东西来避免混乱,但像self论点一样,它可以任意命名.

以下是该方法的一个示例:

def with_this_arg(func):
    def wrapped(*args, **kwargs):
        return func(wrapped, *args, **kwargs)
    return wrapped

@with_this_arg
def hi(this, that):
    # other code...
    this.bye = 2 * that  # Create function attribute.
    sigh = 10

hi(21)
print(hi.bye)  # -> 42
Run Code Online (Sandbox Code Playgroud)

  • 不客气,但我必须补充一点,这种做法很不寻常.可能很难调试,并使代码难以维护 - 因为它基本上与使用全局变量相同,并且长期[被认为是有害的](http://c2.com/cgi/wiki?GlobalVariablesConsideredHarmful) . (12认同)
  • @ erm3nda:根据定义,`hi()`函数没有返回值,因此它有效地返回`None`,它被认为是'False`值,因此`if`不执行条件`print`语句. (2认同)

Joh*_*ohn 7

问题是你将x设置为字符串后调用print x.bye.运行x = hi()时运行hi()并将x的值设置为5(bye的值;它不会将x的值设置为对bye变量本身的引用).EX:bye = 5; x = bye; bye = 4; print x;打印5,而不是4

此外,你不必运行hi()两次,只是运行x = hi(),而不是hi();x=hi()(你运行它的方式是运行hi(),没有做任何结果值为5,然后重新运行相同的hi()和将值5保存到x变量.

所以完整的代码应该是

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

如果要返回多个变量,一个选项是使用列表或字典,具体取决于您的需要.

例如:

def hi():
    something
    xyz = { 'bye': 7, 'foobar': 8}
    return xyz
x = hi()
print x['bye']
Run Code Online (Sandbox Code Playgroud)

更多关于python词典的更多信息,请访问http://docs.python.org/2/tutorial/datastructures.html#dictionaries