Python:从内部获取对函数的引用 [英] Python: getting a reference to a function from inside itself

查看:167
本文介绍了Python:从内部获取对函数的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我定义一个函数:

If I define a function:

def f(x):
    return x+3

我可以稍后将对象存储为函数的属性,如下所示:

I can later store objects as attributes of the function, like so:

f.thing="hello!"

我想从函数本身的代码里面做这件事。问题是,我如何从内部获取对函数的引用?

I would like to do this from inside the code of the function itself. Problem is, how do I get a reference to the function from inside itself?

推荐答案

同样,只需使用它的名称即可。

The same way, just use its name.

>>> def g(x):
...   g.r = 4
...
>>> g
<function g at 0x0100AD68>
>>> g(3)
>>> g.r
4

这篇关于Python:从内部获取对函数的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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