為什么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'}
uj5u.com熱心網友回復:
為了“系結” 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版本
示例輸出:
$ python3 t.py
<__main__.C object at 0x7f3051529dc0> (1,) {'a': 2}
uj5u.com熱心網友回復:
我不確定你的實際要求。但是一個簡單的方法是 letmethod僅僅參考一個真正的方法:
class ClassWithCallable:
method = Callable.__call__
從那時起,
instance = ClassWithCallable()
instance.method('some', data='data')
按預期給出:
<__main__.ClassWithCallable object at 0x0000023542A76548> ('some',) {'data': 'data'}
Where is `ClassWithCallable` instance?
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/466419.html
標籤:Python python-3.x
下一篇:python中串列追加的差異
