クラスのインスタンスが割り当てられるたびに追跡するために、printステートメント/ pdb /などを使用できるようにするオーバーライドできるメソッドはありますか? いくつかのオブジェクトを unpickle しているときに、どちらも持っていない、__setstate__
または__init__
それらを呼び出したことがないものを取得しているようです。__new__
で作成したすべてのオブジェクトの ID をオーバーライドして出力しようとしました__new__
が、出力されなかった ID を持つオブジェクトにまだ遭遇しています。
編集:これは、クラスとそれ自体__new__
を除くすべてのスーパークラスを変更(インスツルメンテーション)するために使用するコードです。object
class Allocator:
def __init__(self, my_class):
self.my_class = my_class
self.old_new = my_class.__new__
def new(self, * args, ** kargs):
rval = self.old_new(*args, ** kargs)
#rval = super(self.my_class,cls).__new__(cls)
print 'Made '+str(self.my_class)+' with id '+str(id(rval))
return rval
def replace_allocator(cls):
if cls == object:
return
setattr(cls,'__new__',Allocator(cls).new)
print cls.__base__
try:
for parent in cls.__base__:
replace_allocator(parent)
except:
replace_allocator(cls.__base__)
メイン スクリプトにインポートされるとすぐに、クラスの親クラスで replace_allocator を呼び出します。私のクラスには__new__
、ID も出力するカスタムがあります。