函数是否有引用自身的通用方法? [英] Is there a generic way for a function to reference itself?

查看:23
本文介绍了函数是否有引用自身的通用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can access a python function's attribute inside of function itself by below code:

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

但是,如果上面的aa()函数是写其他代码的模板,比如bb(),我要写:

However, if above aa() function is a template for write other code, say bb(), I have to write:

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

在类方法中是否有类似于 self 参数的指针",以便我可以编写这样的代码?

Is there a "pointer" similar to the self argument in a class method so I could write code like this?

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

我搜索了一下,发现有人说用class来解决这个问题,但是重新定义所有已有的函数可能有点麻烦.有什么建议吗?

I searched and found someone said to use the class to solve this problem, but that may be a trouble to redefine all the existing functions. Any suggestions?

推荐答案

函数没有通用的方式来引用自身.考虑使用装饰器代替.如果您想要的只是打印有关可以使用装饰器轻松完成的功能的信息:

There is no generic way for a function to refer to itself. Consider using a decorator instead. If all you want as you indicated was to print information about the function that can be done easily with a decorator:

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

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

If you really do need to reference the function, then just add it to the function arguments:

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 的自省功能正常工作:

You can also write a simpler (and probably faster) decorator that will make the wrapped function work correctly with Python's introspection:

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__ 方法,用于创建绑定方法.装饰器简单地使用现有方法使函数成为其自身的绑定方法.它仅适用于独立函数,如果您希望方法能够引用自身,则必须执行更类似于原始解决方案的操作.

This leverages Python's descriptor protocol: functions have a __get__ method that is used to create bound methods. The decorator simply uses the existing method to make the function a bound method of itself. It will only work for standalone functions, if you wanted a method to be able to reference itself you would have to do something more like the original solution.

这篇关于函数是否有引用自身的通用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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