python - 方法调用本身没有方法名?

标签 python

class C:
  def M:
    self.M()

可以代替self.M,如self.__FUNC__吗?所以当函数名改变时不会改变函数内部的代码

最佳答案

没有任何内置内容,但您可以使用装饰器来完成此操作,以确保在每次调用原始函数之前定义该属性。您还需要保存和恢复该属性,以防多个方法被类似地修饰并且它们相互调用。

import functools

def decorator(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        save = getattr(self, '_FUNC_', None)
        self._FUNC_ = func
        retval = func(self, *args, **kwargs)
        self._FUNC_ = save
        if save:  self._FUNC_ = save
        else: delattr(self, '_FUNC_')
        return retval
    return wrapper

class C(object):
    @decorator
    def M(self, i):
        if i > 0:
            print i,
            self._FUNC_(self, i-1)  # explicit 'self' argument required
        else:
            print '- Blast Off!'

C().M(3)  # -> 3 2 1 - Blast Off!

请注意,self._FUNC_不是绑定(bind)方法,因为装饰器是在构造类时调用的。这意味着每当从装饰方法中调用时,都必须将 self 显式传递给该方法作为第一个参数。

更新

解决这个问题的一种方法是在第一次实际调用该方法之前不创建包装函数(然后保存它以减少将来的开销)。这将允许它像任何其他方法一样被调用。我从 PythonDecoratorLibrary 找到了解决方案示例标题为 Class method decorator using instance .

import functools

def decorator(f):
    """
    Method decorator specific to the instance.

    Uses a special descriptor to delay the definition of the method wrapper.
    """
    class SpecialDescriptor(object):
        def __init__(self, f):
            self.f = f

        def __get__(self, instance, cls):
            if instance is None:  # unbound method request?
                return self.make_unbound(cls)
            return self.make_bound(instance)

        def make_unbound(self, cls):
            @functools.wraps(self.f)
            def wrapper(*args, **kwargs):
                raise TypeError('unbound method {}() must be called with {} '
                                'instance as first argument'.format(
                                                                self.f.__name__,
                                                                cls.__name__))
            return wrapper

        def make_bound(self, instance):
            @functools.wraps(self.f)
            def wrapper(*args, **kwargs):
                save = getattr(instance, '_FUNC_', None)
                instance._FUNC_ = getattr(instance, self.f.__name__)
                retval = self.f(instance, *args, **kwargs)
                if save:  instance._FUNC_ = save  # restore any previous value
                else: delattr(instance, '_FUNC_')
                return retval

            # instance no longer needs special descriptor, since method is now
            # wrapped, so make it call the wrapper directly from now on
            setattr(instance, self.f.__name__, wrapper)
            return wrapper

    return SpecialDescriptor(f)

class C(object):
    @decorator
    def M(self, i):
        if i > 0:
            print i,
            self._FUNC_(i-1)  # No explicit 'self' argument required
        else:
            print '- Blast Off!'

C().M(3)  # -> 3 2 1 - Blast Off!

关于python - 方法调用本身没有方法名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25351042/

相关文章:

python - Jedi-vim 自动补全 python3.6 virtualenv 不工作

python - 关于python变量作用域的疑惑

python - conda 'ImportError: No module named ruamel.yaml.comments'

python - 获取 2 个日期范围内的最后日期

python - 将 CSV 值转换为 numpy 数组,其中字段作为数组索引

Python Ansible API 仅在控制节点中执行命令,不在远程节点中执行命令

python pandas - 生成具有多个条件的 View /复制警告过滤数据框

python - Python 中的噪音?

python - 非阻塞 Matplotlib 动画

python - ManytoMany 与 django Rest 相关