没有方法名称的方法调用本身?

严零
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_不是绑定方法,因为在构造类时会调用装饰器。这意味着self无论何时从修饰的方法中调用a,都必须将其作为第一个参数显式传递给该方法。

更新

解决该问题的一种方法是直到第一次实际调用该方法时才创建包装器函数(然后保存该方法以减少将来的开销)。这将允许它像其他任何方法一样被调用。我从PythonDecoratorLibrary示例中获得了一个解决方案的想法,该示例标题为使用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!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章