logo

Python のデストラクター

ユーザーはオブジェクトを破棄するために Destructor を呼び出します。 Python では、開発者は C++ 言語で必要になるほどデストラクターを必要としない場合があります。これは、Python にはメモリ管理を自動的に処理する機能を持つガベージ コレクターがあるためです。

この記事では、Python のデストラクターがどのように機能するのか、またユーザーがデストラクターをいつ使用できるのかについて説明します。

__の__() 関数はデストラクター関数として使用されます。 パイソン 。ユーザーは、 __の__() オブジェクトの参照がすべて削除され、ガベージ コレクションされたときに関数が実行されます。

構文:

JavaはCSVを読み取ります
 def __del__(self): # the body of destructor will be written here. 

ユーザーは、オブジェクトが参照から外れたとき、またはコードが終了したときに、オブジェクトへの参照も削除されることに注意する必要があります。

次の例では、__del__() 関数と del キーワードを使用してオブジェクトのすべての参照を削除し、デストラクターが自動的に関与するようにします。

例えば:

 # we will illustrate destructor function in Python program # we will create Class named Animals class Animals: # we will initialize the class def __init__(self): print('The class called Animals is CREATED.') # now, we will Call the destructor def __del__(self): print('The destructor is called for deleting the Animals.') object = Animals() del object 

出力:

 The class called Animals is CREATED. The destructor is called for deleting the Animals. 

説明 -

文字列をint Javaに変換する方法

上記のコードでは、オブジェクトへの参照が削除されたとき、またはプログラムが終了した後に、デストラクターが呼び出されています。これは、オブジェクトの参照カウントがゼロになるのではなく、オブジェクトがスコープ外に出てもゼロになることを意味します。次の例を示して説明します。

プログラムの終了後にデストラクターが呼び出されていることにも注意してください。

例:

 # We will create Class named Animals class Animals: # Initialize the class def __init__(self): print('The class called Animals is CREATED.') # now, we will Call the destructor def __del__(self): print('The destructor is called for deleting the Animals.') def Create_object(): print('we are creating the object') object = Animals() print('we are ending the function here') return object print('we are calling the Create_object() function now') object = Create_object() print('The Program is ending here') 

出力:

部分文字列メソッドJava
 we are calling the Create_object() function now we are creating the object The class called Animals is CREATED. we are ending the function here The Program is ending here The destructor is called for deleting the Animals. 

次の例では、 function() が呼び出されると、クラス Zebra のインスタンスが作成され、それ自体がクラス Lion に渡され、その後、クラス Zebra への参照が設定され、結果は次のようになります。循環参照。

例:

 class Animals: # we will initialize the class def __init__(self): print(' The class called Animals is CREATED.') class Lion: def __init__(self, zebraa): self.zebra = zebraa class Zebra: def __init__(self): self.lion = Lion(self) def __del__(self): print('Zebra is dead') def function(): zebra = Zebra() function() 

出力:

 Zebra is dead 

一般に、この種の循環参照の検出に使用される Python のガベージ コレクターも参照を削除します。ただし、上記の例では、カスタム デストラクターは、このアイテムを収集不可能としてマークするために使用されています。

簡単に言うと、ガベージ コレクターはオブジェクトを破棄する順序がわからないため、そのままにしてしまうことを意味します。したがって、ユーザーのインスタンスがこの循環参照に関与している場合、アプリケーションが実行されている限り、それらのインスタンスはメモリに保存されたままになります。

結論

この記事では、Python のデストラクタの機能と、メモリから参照がすでに削除されているオブジェクトを削除するためにユーザーがデストラクタを使用する方法について説明しました。