今回は、Pythonのdelattr()関数に注目します。
Python の delattr() メソッドを使い始める
オブジェクト指向プログラミングにおいて、クラスは属性や振る舞いをラップした実体であり、オブジェクトを使って同じものを表現することができます。
Pythonはオブジェクト指向の言語なので、クラスの機能は存在します。
属性を作成し、振る舞いを定義しているときに、Pythonのクラスの特定の属性を削除したい場面に出くわすかもしれません。
このようなときにPythonのdelattr()が登場します。
delattr()関数は、特定のクラスに関連付けられている属性を削除するために使用されます。
構文は以下の通りです。
delattr(object, attribute)
|
例えば、以下の様になります。
class Info:
name = "Python"
lang = "Python"
site = "Google"
obj = Info()
print(obj.name)
delattr(Info, 'lang')
|
結果は以下の通りです。
Python |
上記の例では、次のような属性を持つクラスInfoを作成しました。
- 名前 = Python
- 言語 = Python
- サイト = google
さらに、以下のコマンドを使用して、クラス ‘Info’ のオブジェクトを作成しました。
obj = <classname>()
|
オブジェクトを作成した後、delattr()関数を使用して属性’lang’を削除しています。
delattr() によるエラーと例外発生
属性を削除した後、そのオブジェクトにアクセスしようとすると、コンパイラは AttributeError をスローします。
例えば、以下の様になります。
class Info:
name = "Python"
lang = "Python"
site = "Google"
obj = Info()
delattr(Info, 'lang')
print(obj.lang)
|
結果は以下の通りです。
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)<ipython-input-5-699f50a1e7c7> in <module>
5 obj = Info()
6 delattr(Info, 'lang')
----> 7 print(obj.lang)
AttributeError: 'Info' object has no attribute 'lang'
|
Pythonのdel演算子で属性を削除する
Python の del 演算子`は、オブジェクトを介さずに直接クラスの属性を削除するために使うこともできます。
構文は以下の通りです。
del Class-name.attribute-name
|
例えば、以下の様になります。
class Info:
name = "Python"
lang = "Python"
site = "Google"
print("Attribute before deletion:,Info.lang)
del Info.lang
print("Attribute after deletion:,Info.lang)
|
結果は以下の通りです。
Attribute before deletion: Python
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)<ipython-input-16-9d8ed21690ff> in <module>
5 print("Attribute before deletion:,Info.lang)
6 del Info.lang
----> 7 print("Attribute after deletion:,Info.lang)
AttributeError: type object 'Info' has no attribute 'lang'
|
Python delattr() メソッドと Python del 演算子の比較
Python delattr()メソッドは、属性の動的な削除という点ではPython del演算子よりも効率的です。
一方、Python del演算子はPython delattr()メソッドと比較して、高速に処理を実行することができます。
まとめ
以上、Pythonのdelattr()メソッドとdel演算子を使って、属性の削除を行う方法を説明しました。