如何将self传入被装饰的Python类方法?
解决Python装饰器中实例方法self自动传入的问题
问题出在你实现的类装饰器没有遵循Python的描述符协议——实例方法之所以能自动传入self,是因为原生函数本身是描述符,当通过实例访问时会触发__get__方法完成实例绑定。你的Public类缺少这个逻辑,导致装饰后的方法无法自动绑定实例。
修改后的装饰器代码
class Public: def __init__(self, method): self.method = method def __get__(self, instance, owner): # 通过实例访问方法时,返回绑定了当前实例的调用逻辑 if instance is None: return self return lambda *args, **kwargs: self.method(instance, *args, **kwargs) def __call__(self, *args, **kwargs): return self.method(*args, **kwargs)
测试原示例代码
class Test: @Public def test(self): return "Hello" class Test1(Test): def __init__(self): super().__init__() print(self.test()) x = Test1() # 输出: Hello
原理说明
__get__是描述符协议的核心方法,当你通过self.test访问装饰后的方法时,Python会自动调用Public实例的__get__,传入当前实例(也就是需要绑定的self)和类对象。- 在
__get__中,我们返回一个lambda函数,把当前实例作为第一个参数传给被装饰的方法,模拟了原生实例方法的自动绑定逻辑。 - 如果直接通过类访问方法(比如
Test.test),instance参数为None,此时返回装饰器自身,保留直接调用的能力。
另外,你原代码中type(method).__name__ == 'function'的判断可以省略,因为装饰器装饰类方法时,传入的必然是函数对象。
内容的提问来源于stack exchange,提问作者Tyson Chicken
相关产品推荐
相关产品推荐

