繁体   English   中英

函数是否有引用自身的通用方法?

[英]Is there a generic way for a function to reference itself?

我可以通过以下代码在函数本身内部访问python函数的属性:

def aa():
    print aa.__name__
    print aa.__hash__
    # other simliar

但是,如果上述aa()函数是用于编写其他代码的模板,例如bb() ,我必须编写:

def bb():
    print bb.__name__
    print bb.__hash__
    # other simliar

类方法中是否存在类似于self参数的“指针”,因此我可以编写这样的代码?

def whatever():
    print self.__name__
    print self.__hash__
    # other simliar

我搜索后发现有人说可以使用该类来解决此问题,但是重新定义所有现有功能可能会很麻烦。 有什么建议么?

函数没有通用的方式引用自身。 考虑改用装饰器。 如果您想要的只是打印有关可以通过装饰器轻松完成的功能的信息,请执行以下操作:

from functools import wraps
def showinfo(f):
    @wraps(f)
    def wrapper(*args, **kwds):
         print(f.__name__, f.__hash__)
         return f(*args, **kwds)
    return wrapper

@showinfo
def aa():
    pass

如果确实需要引用该函数,则只需将其添加到函数参数中即可:

def withself(f):
    @wraps(f)
    def wrapper(*args, **kwds):
        return f(f, *args, **kwds)
    return wrapper

@withself
def aa(self):
      print(self.__name__)
      # etc.

编辑以添加备用装饰器

您还可以编写一个更简单(可能更快)的装饰器,使包装函数在Python的自省下正常工作:

def bind(f):
    """Decorate function `f` to pass a reference to the function
    as the first argument"""
    return f.__get__(f, type(f))

@bind
def foo(self, x):
    "This is a bound function!"
    print(self, x)


>>> foo(42)
<function foo at 0x02A46030> 42
>>> help(foo)
Help on method foo in module __main__:

foo(self, x) method of builtins.function instance
    This is a bound function!

这利用了Python的描述符协议:函数具有__get__方法,该方法用于创建绑定方法。 装饰器仅使用现有方法使函数成为自身的绑定方法。 它仅适用于独立功能,如果您想要一种能够引用自身的方法,则必须做更多类似于原始解决方案的事情。

http://docs.python.org/library/inspect.html看起来很有希望:

import inspect
def foo():
     felf = globals()[inspect.getframeinfo(inspect.currentframe()).function]
     print felf.__name__, felf.__doc__

您还可以使用sys模块来获取当前函数的名称:

import sys
def bar():
     felf = globals()[sys._getframe().f_code.co_name]
     print felf.__name__, felf.__doc__

您至少可以在第一行说出self = bb ,然后仅在更改函数名称时才需要更改该行,而不是其他所有引用。

我的代码编辑器也以与对类相同的方式突出显示变量self

如何快速制作一个自己的“自我”名称,如下所示:

>>> def f():
...     self = f
...     print "My name is ", self.__name__, "and I am", self.__hash__
...
>>> f()
My name is  f and I am <method-wrapper '__hash__' of function object at 0x00B50F30>
>>> x = f
>>> x()
My name is  f and I am <method-wrapper '__hash__' of function object at 0x00B50F30>
>>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM