如何Python函数访问自己的属性? [英] how can python function access its own attributes?

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

问题描述

是有可能访问在函数范围内的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)

感谢

更新:

我想下面的工作还:

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被删除,则函数失败。更复杂的检查建议以同样的方式失败。

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

在上面,是一个局部变量,因此没有执行全球查找。但是,我们不能写code原样,因为˚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.

下面是一个简单的装饰为你做到这一点。请注意,参数必须最后一个出现,不像方法,其中第一。这也意味着,你必须给一个默认值,如果你的任何其他参数取默认值。

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'

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

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