Python 在不使用“全局”的情况下访问函数外部的函数变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19326004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:27:03  来源:igfitidea点击:

Access a function variable outside the function without using "global"

pythonlocal-variables

提问by askance

I am trying to access a local function variable outside the function in Python. So, for example,

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

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

hi()
print bye

The above works fine as it should. Since I want to find out if I can access byeoutside hi()without using global bye, I tried:

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

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

hi()
x = hi()
print x.bye 

The above gives AttributeError: 'NoneType' object has no attribute 'bye'.

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

Then, I tried:

然后,我尝试:

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

This time it doesn't give even an error.

这次它甚至没有给出错误。

So, is there a way to access a local function variable (bye) outside its function (hi()) without using globals and without printing out variable sighas well? (Question was edited to include sighafter @hcwhsa 's comment below.

那么,有没有办法在不使用全局变量和不打印变量的情况下访问其函数(bye)之外的局部函数变量()?(问题已编辑为包含在@hcwhsa 下面的评论之后。hi()sighsigh

采纳答案by martineau

You could do something along these lines (which worked in both Python v2.7.17 and v3.8.1 when I tested it/them):

你可以按照这些方式做一些事情(当我测试它/它们时,它在 Python v2.7.17 和 v3.8.1 中都有效):

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

hi()
print(hi.bye)  # -> 42

Functions are objects in Python and can have arbitrary attributes assigned to them.

函数是 Python 中的对象,可以为它们分配任意属性。

If you're going to be doing this kind of thing often, you could implement something more generic by creating a function decorator that adds a thisargument to each call to the decorated function.

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

This additional argument will give functions a way to reference themselves without needing to explicitly embed (hardcode) it into their definition and is similar to the instance argument that class methods automatically receive as their first argument which is usually named self— I picked something different to avoid confusion, but like the selfargument, it can be named whatever you wish.

这个额外的参数将为函数提供一种引用自身的方法,而无需将其显式嵌入(硬编码)到它们的定义中,并且类似于类方法自动接收作为它们的第一个参数的实例参数,该参数通常被命名self——我选择了一些不同的东西来避免混乱,但就像self论证一样,它可以随心所欲地命名。

Here's an example of that approach:

下面是这种方法的一个例子:

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

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

hi(21)
print(hi.bye)  # -> 42

回答by John

The problem is you were calling print x.bye after you set x as a string. When you run x = hi()it runs hi() and sets the value of x to 5 (the value of bye; it does NOT set the value of x as a reference to the bye variable itself). EX: bye = 5; x = bye; bye = 4; print x;prints 5, not 4

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

Also, you don't have to run hi() twice, just run x = hi(), not hi();x=hi()(the way you had it it was running hi(), not doing anything with the resulting value of 5, and then rerunning the same hi() and saving the value of 5 to the x variable.

此外,您不必运行 hi() 两次,只需运行x = hi(),而不是hi();x=hi()(您运行 hi() 的方式,不对结果值 5 执行任何操作,然后重新运行相同的 hi() 和将 5 的值保存到 x 变量中。

So full code should be

所以完整的代码应该是

def hi():
    something
    something
    bye = 5
    return bye 
x = hi()
print x

If you wanted to return multiple variables, one option would be to use a list, or dictionary, depending on what you need.

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

ex:

前任:

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

more on python dictionaries at http://docs.python.org/2/tutorial/datastructures.html#dictionaries

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

回答by Thomas Corll

You could do something along this lines:

您可以按照以下方式做一些事情:

def static_example():
   if not hasattr(static_example, "static_var"):
       static_example.static_var = 0
   static_example.static_var += 1
   return static_example.static_var

print static_example()
print static_example()
print static_example()

回答by Allan Mwesigwa

 def hi():
     bye = 5
     return bye  

print hi()

回答by Ivan Nepomnyashchikh

I've experienced the same problem. One of the responds to your question led me to the following idea (which worked eventually). I use Python 3.7.

我也遇到过同样的问题。对您问题的回答之一使我想到了以下想法(最终奏效)。我使用 Python 3.7。

    # just an example 
    def func(): # define a function
       func.y = 4 # here y is a local variable, which I want to access; func.y defines 
                  # a method for my example function which will allow me to access 
                  # function's local variable y
       x = func.y + 8 # this is the main task for the function: what it should do
       return x

    func() # now I'm calling the function
    a = func.y # I put it's local variable into my new variable
    print(a) # and print my new variable

Then I launch this program in Windows PowerShell and get the answer 4. Conclusion: to be able to access a local function's variable one might add the name of the function and a dot before the name of the local variable (and then, of course, use this construction for calling the variable both in the function's body and outside of it). I hope this will help.

然后我在 Windows PowerShell 中启动这个程序并得到答案 4. 结论:为了能够访问局部函数的变量,可以在局部变量的名称前添加函数的名称和一个点(然后,当然,使用此构造调用函数体内和函数外的变量)。我希望这将有所帮助。