そのクラスのメソッドとしてデコレータを定義するクラスを定義しました。デコレーター自体は、装飾されたメソッドを置き換える 2 番目のクラスの呼び出し可能なインスタンスを作成します。装飾されたメソッドは実際にはクラスになっているので、メソッドを呼び出すことができます。私の(架空の、最小限の)例では、メソッドごとのコールバックのカスタム最大数でコールバックを登録したいと考えています。
class CallbackAcceptor:
def __init__(self, max_num_callbacks, func):
self._func = func
self._max_num_callbacks = max_num_callbacks
self._callbacks = []
def __call__(self, *args, **kwargs):
# This ends up being called when the decorated method is called
for callback in self._callbacks:
print(f"Calling {callback.__name__}({args}, {kwargs})")
callback(*args, **kwargs)
return self._func(*args, **kwargs) # this line is the problem, self is not bound
def register_callback(self, func):
# Here I can register another callback for the decorated function
if len(self._callbacks) < self._max_num_callbacks:
self._callbacks.append(func)
else:
raise RuntimeError(f"Can not register any more callbacks for {self._func.__name__}")
return func
class MethodsWithCallbacksRegistry:
def __init__(self):
self.registry = {} # Keep track of everything that accepts callbacks
def accept_callbacks(self, max_num_callbacks: int = 1):
def _make_accept_callbacks(func):
# Convert func to an CallbackAcceptor instance so we can register callbacks on it
if func.__name__ not in self.registry:
self.registry[func.__name__] = CallbackAcceptor(max_num_callbacks=max_num_callbacks, func=func)
return self.registry[func.__name__]
return _make_accept_callbacks
すべてが関数に対して期待どおりに機能しますが、クラス インスタンスが装飾されたメソッドにバインドされていないため、クラス メソッドを装飾すると壊れます。
registry = MethodsWithCallbacksRegistry()
@registry.accept_callbacks(max_num_callbacks=1)
def bar(i):
return i * 10
@bar.register_callback
def bar_callback(*args, **kwargs):
print("Bar Callback")
print(bar(i=10)) # Works fine, prints "Bar Callback" and then 100
コールバックを受け入れるメソッドを定義すると、次のようになります。
class Test:
@registry.accept_callbacks(max_num_callbacks=1)
def foo(self, i):
return i * 2
@Test.foo.register_callback
def foo_callback(*args, **kwargs):
print("Foo Callback")
self を明示的に渡すと機能しますが、インスタンスがバインドされていると仮定するだけでは機能しません。
t = Test()
# Note that I pass the instance of t explicitly as self
Test.foo(t, i=5) # Works, prints "Foo Callback" and then 10
t.foo(t, i=5) # Works, prints "Foo Callback" and then 10
t.foo(i=5) # Crashes, because self is not passed to foo
これはトレースバックです:
Traceback (most recent call last):
File "/home/veith/.PyCharmCE2019.3/config/scratches/scratch_4.py", line 62, in <module>
t.foo(i=5)
File "/home/veith/.PyCharmCE2019.3/config/scratches/scratch_4.py", line 13, in __call__
return self._func(*args, **kwargs) # this line is the problem, self is not bound
TypeError: foo() missing 1 required positional argument: 'self'
私はいつもそれt.foo(i=5)
が記述子を経由するための基本的な構文糖衣Test.foo(t, i=5)
だと思っていますが、それは間違っているようです。だからここに私の質問があります:
- これが期待どおりに機能しない理由は何ですか?
- それを機能させるにはどうすればよいですか?
ありがとうございました!
PS: 私は python 3.8 を使用しています