[英]Instance is not passed to the `__call__` function of a callable class
为什么ClassWithCallable
实例没有传递给__call__
function? 我怎样才能做到这一点?
class Callable:
def __call__(self, *args, **kwargs):
print(self, args, kwargs)
print('Where is `ClassWithCallable` instance?')
class ClassWithCallable:
method = Callable()
instance = ClassWithCallable()
instance.method('some', data='data')
instance.method(instance, 'some', data='data') # ugly :(
Output:
<__main__.Callable object at 0x7f2b4e5ecfd0> ('some',) {'data': 'data'}
Where is `ClassWithCallable` instance?
<__main__.Callable object at 0x7fef7fa49fd0> (<__main__.ClassWithCallable object at 0x7fef7fa49fa0>, 'some') {'data': 'data'}
为了“绑定” self
,您需要实现描述符协议(类似于实际方法的工作方式!)
class Callable:
def __init__(self, inst=None):
self.inst = inst
def __get__(self, instance, owner):
return type(self)(instance)
def __call__(self, *args, **kwargs):
print(self.inst, args, kwargs)
class C:
callable = Callable()
C().callable(1, a=2)
当属性被检索时,它调用你的描述符的__get__
——我的实现返回一个“绑定”版本的Callable
,其中self.inst
是你寻找的self
例如 output:
$ python3 t.py
<__main__.C object at 0x7f3051529dc0> (1,) {'a': 2}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.