-
LabEx 環境で VS Code エディタを開きます。
-
~/project
ディレクトリに hasattr_example.py
という名前の新しいファイルを作成します。
touch ~/project/hasattr_example.py
-
エディタで hasattr_example.py
ファイルを開き、次のコードを追加します。
import math
## Check if the 'sqrt' function exists in the 'math' module
if hasattr(math, 'sqrt'):
print("The 'sqrt' function exists in the 'math' module.")
result = math.sqrt(25)
print("The square root of 25 is:", result)
else:
print("The 'sqrt' function does not exist in the 'math' module.")
## Check if the 'pi' constant exists in the 'math' module
if hasattr(math, 'pi'):
print("The 'pi' constant exists in the 'math' module.")
print("The value of pi is:", math.pi)
else:
print("The 'pi' constant does not exist in the 'math' module.")
## Check for a non-existent attribute
if hasattr(math, 'non_existent_attribute'):
print("The 'non_existent_attribute' exists in the 'math' module.")
else:
print("The 'non_existent_attribute' does not exist in the 'math' module.")
このコードでは、まず math
モジュールをインポートします。次に、hasattr()
を使用して、math
モジュールに sqrt
関数と pi
定数が存在するかどうかをチェックします。また、存在しない属性をチェックして、hasattr()
がそのケースをどのように処理するかを確認します。
-
ターミナルで次のコマンドを使用してスクリプトを実行します。
python ~/project/hasattr_example.py
次の出力が表示されるはずです。
The 'sqrt' function exists in the 'math' module.
The square root of 25 is: 5.0
The 'pi' constant exists in the 'math' module.
The value of pi is: 3.141592653589793
The 'non_existent_attribute' does not exist in the 'math' module.
この出力は、hasattr()
を使用してモジュール内の関数や定数の存在をチェックする方法を示しています。
-
次に、カスタムオブジェクトで hasattr()
を使用してみましょう。スクリプトを次のように変更します。
class MyClass:
def __init__(self):
self.attribute1 = "Hello"
def my_method(self):
return "World"
obj = MyClass()
## Check if the object has the attribute 'attribute1'
if hasattr(obj, 'attribute1'):
print("The object has the attribute 'attribute1'.")
print("The value of attribute1 is:", obj.attribute1)
else:
print("The object does not have the attribute 'attribute1'.")
## Check if the object has the method 'my_method'
if hasattr(obj, 'my_method'):
print("The object has the method 'my_method'.")
print("The result of my_method is:", obj.my_method())
else:
print("The object does not have the method 'my_method'.")
## Check for a non-existent attribute
if hasattr(obj, 'non_existent_attribute'):
print("The object has the attribute 'non_existent_attribute'.")
else:
print("The object does not have the attribute 'non_existent_attribute'.")
-
スクリプトを再度実行します。
python ~/project/hasattr_example.py
次の出力が表示されるはずです。
The object has the attribute 'attribute1'.
The value of attribute1 is: Hello
The object has the method 'my_method'.
The result of my_method is: World
The object does not have the attribute 'non_existent_attribute'.
これは、hasattr()
を使用してカスタムオブジェクトの属性やメソッドの存在をチェックすることもできることを示しています。