私はPython 3.5.1を使用しています。 私はライブラリを作成しました。特定の状況(ファイルが直接実行されたとき、つまり__name__ == '__main__'
)では、クラスの1つに特定のメソッドをデコレートしたいと考えています。これまで作成することができるすべてのインスタンスを装飾する必要があります。私はそれが非侵襲的なやり方でやりたい、つまり理想的には私の図書館のクラスは特別なコードを必要としないでしょう。Pythonでクラスのすべてのインスタンスにパッチを適用する
def patch(clazz, name, replacement):
def wrap_original(orig):
# when called with the original function, a new function will be returned
# this new function, the wrapper, replaces the original function in the class
# and when called it will call the provided replacement function with the
# original function as first argument and the remaining arguments filled in by Python
def wrapper(*args, **kwargs):
return replacement(orig, *args, **kwargs)
return wrapper
orig = getattr(clazz, name)
setattr(clazz, name, wrap_original(orig))
def replacement_function(orig, self, ... other argumnents ...):
# orig here is the original function, so can be called like this:
# orig(self, ... args ...)
pass
patch(mylib.MyClass, 'method_name', replacemment_function)
驚くべきことに、私はまだクラスメソッドでそれをテストしていないが、このコードは、動作しますが、私はドン」:しばらく
は、私は私の要件を満たしている。このような何かを実装するために管理しましたそれは今必要です。また、パッチの前に作成されたインスタンスにパッチを当てますが、それが良いかどうかはまだ分かりませんが、d上記のコードは間違いなく難しいですが、私は書いた後、それは、説明のコメントを書くために。私はもっと簡単なことが大好きです。
質問:Pythonライブラリには、このようなコードが不要になり、既に実装しているものが実装されていますが、それより優れていますか?
これは私が[ここ](https://github.com/host-anshu/simpleInterceptor/blob/master/interceptor.py)のやり方に似ています。私はまた、もっと簡単なものを考え出すことができませんでした。 –