__del__ メソッドの実装とテスト
このステップでは、__del__ メソッドについて学びます。このメソッドはファイナライザ(finalizer)またはデストラクタ(destructor)と呼ばれます。オブジェクトの参照カウントがゼロになったとき、つまり Python のガベージコレクタによって破棄されようとしているときに呼び出されます。ネットワーク接続やファイルハンドルを閉じるなど、クリーンアップタスクによく使用されます。
del ステートメントを使用してオブジェクトへの参照を削除できます。最後の参照がなくなると、__del__ が自動的に呼び出されます。
オブジェクトがいつ破棄されるかを確認するために、Dog クラスに __del__ メソッドを追加してみましょう。
再度 dog_cat.py ファイルを開きます。ファイル全体の内容を以下のコードに置き換えてください。このバージョンでは、モジュールがインポートされたときにインスタンスが作成されるのを避けるため、Dog インスタンスを作成するコードは削除され、Dog クラスに __del__ メソッドが追加されています。
## File Name: dog_cat.py
class Animal:
def __init__(self, name):
self._name = name
def say(self):
print(self._name + ' is saying something')
class Dog(Animal):
def __new__(cls, name, age):
instance = super().__new__(cls)
return instance
def __init__(self, name, age):
super().__init__(name)
self.age = age
def say(self):
print(self._name + ' is making a sound: wang wang wang...')
## このメソッドを Dog クラスに追加します
def __del__(self):
print(f'The Dog object {self._name} is being deleted.')
dog_cat.py ファイルを保存します。
次に、この動作をテストするための別のスクリプトを作成します。ファイルエクスプローラーから test_del.py ファイルを開きます。
test_del.py に以下のコードを追加します。このスクリプトは 2 つの Dog インスタンスを作成し、そのうちの 1 つを明示的に削除します。
## File Name: test_del.py
from dog_cat import Dog
import time
print("Creating two Dog objects: d1 and d2.")
d1 = Dog('Tom', 3)
d2 = Dog('John', 5)
print("\nDeleting reference to d1...")
del d1
print("Reference to d1 deleted.")
## ガベージコレクタは即座に実行されない場合があります。
## 実行時間を確保するために短い遅延を追加します。
time.sleep(1)
print("\nScript is about to end. d2 will be deleted automatically.")
ファイルを保存します。次に、ターミナルで test_del.py スクリプトを実行します。
python ~/project/test_del.py
出力を観察してください。del d1 が呼び出された後、Tom の __del__ メッセージが表示されます。d2 オブジェクトはスクリプト終了時にガベージコレクトされるため、John のメッセージは最後に出力されます。
Creating two Dog objects: d1 and d2.
Deleting reference to d1...
The Dog object Tom is being deleted.
Reference to d1 deleted.
Script is about to end. d2 will be deleted automatically.
The Dog object John is being deleted.
注意: ガベージコレクションの正確なタイミングは異なる場合があります。__del__ は、del が使用された直後ではなく、オブジェクトが収集されたときに呼び出されます。