Instance没有传递给可调用类的' __call__ '函数



为什么ClassWithCallable实例不传递给__call__函数?我怎样才能做到呢?

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 :(

输出:

<__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__—我的实现返回一个"bound"Callable的版本,其中self.inst是您寻找的self

示例输出:

$ python3 t.py
<__main__.C object at 0x7f3051529dc0> (1,) {'a': 2}

最新更新