在函数外部访问函数变量,而无需使用“全局"变量. [英] Access a function variable outside the function without using "global"

查看:125
本文介绍了在函数外部访问函数变量,而无需使用“全局"变量.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Python函数外部访问局部函数变量.例如,

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

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

hi()
print bye

上面的应该可以正常工作.由于我想确定是否可以在不使用global bye的情况下访问hi()之外的bye,因此我尝试了:

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

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

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

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

然后,我尝试了:

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.

那么,有没有一种方法可以在其函数(hi())之外访问局部函数变量(bye),而无需使用全局变量,也不必打印出变量sigh? (对问题进行了编辑,在以下@hcwhsa的评论后加上sigh.

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

推荐答案

您可以按照以下方式进行操作(在我测试它们时,它们在Python v2.7.17和v3.8.1中均有效):

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

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

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

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

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

如果您将经常做这种事情,则可以通过创建一个函数装饰器来实现更通用的功能,该函数装饰器在装饰函数的每个调用中添加一个this参数.

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 this argument to each call to the decorated function.

此附加参数将为函数提供一种引用自身的方式,而无需将其明确嵌入(硬编码)其定义中,并且类似于类方法自动将其作为第一个参数(通常称为self)自动接收的实例参数—为了避免混淆,我选择了其他方法,但是像self参数一样,可以将其命名为任意名称.

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 self argument, it can be named whatever you wish.

这是该方法的一个示例:

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

这篇关于在函数外部访问函数变量,而无需使用“全局"变量.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆