函数如何访问其自己的属性? [英] How can a function access its own attributes?

查看:106
本文介绍了函数如何访问其自己的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从函数范围内访问python函数对象属性?

例如我们有

def f():
    return SOMETHING

f._x = "foo"
f()           # -> "foo"

现在,如果我们想返回_x属性内容"foo",那将是什么?甚至有可能(简单)

now, what SOMETHING has to be, if we want to have the _x attribute content "foo" returned? if it's even possible (simply)

谢谢

更新:

我还希望进行以下工作:

i'd like the following work also:

g = f
del f
g()          # -> "foo"

更新2:

声明不可能(如果是这种情况)以及原因,比提供一种伪造方法更令人满意.对象与函数的对象不同

Statement that it is not possible (if it is the case), and why, is more satisfying than providing a way how to fake it e.g. with a different object than a function

推荐答案

解决方案

使函数的默认参数之一成为对函数本身的引用.

Solution

Make one of the function's default arguments be a reference to the function itself.

def f(self):
    return self.x
f.func_defaults = (f,)

示例用法:

>>> f.x = 17
>>> b = f
>>> del f
>>> b()
17

说明

原始发布者想要一种不需要全局名称查找的解决方案.简单的解决方案

Explanation

The original poster wanted a solution that does not require a global name lookup. The simple solution

def f():
    return f.x

在每次调用时执行全局变量f的查找,这不符合要求.如果删除了f,则该功能将失败.更复杂的inspect提议以相同的方式失败.

performs a lookup of the global variable f on each call, which does not meet the requirements. If f is deleted, then the function fails. The more complicated inspect proposal fails in the same way.

我们想要的是执行早期绑定并将绑定的引用存储在对象本身内.从概念上讲,以下是我们正在做的事情:

What we want is to perform early binding and store the bound reference within the object itself. The following is conceptually what we are doing:

def f(self=f):
    return self.x

在上面,self是局部变量,因此不执行全局查找.但是,我们无法按原样编写代码,因为当我们尝试将self的默认值绑定到它时,尚未定义f.相反,我们在定义f之后设置默认值.

In the above, self is a local variable, so no global lookup is performed. However, we can't write the code as-is, because f is not yet defined when we try to bind the default value of self to it. Instead, we set the default value after f is defined.

这是一个简单的装饰器,可以为您完成此操作.请注意,self参数必须排在最后,而方法self排在第一位.这也意味着,如果其他任何参数都采用默认值,则必须提供默认值.

Here's a simple decorator to do this for you. Note that the self argument must come last, unlike methods, where self comes first. This also means that you must give a default value if any of your other arguments take a default value.

def self_reference(f):
    f.func_defaults = f.func_defaults[:-1] + (f,)
    return f

@self_reference
def foo(verb, adverb='swiftly', self=None):
    return '%s %s %s' % (self.subject, verb, adverb)

示例:

>>> foo.subject = 'Fred'
>>> bar = foo
>>> del foo
>>> bar('runs')
'Fred runs swiftly'

这篇关于函数如何访问其自己的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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