-
LabEx 環境で VS Code エディタを開きます。
-
~/project
ディレクトリ内の type_check.py
ファイルを編集します。
~/project/type_check.py
-
Dog
クラスを継承する GermanShepherd
という新しいクラスを追加します。この時点での type_check.py
ファイルは次のようになります。
class Dog:
species = "Canis familiaris"
def __init__(self, name, age):
self.name = name
self.age = age
class GermanShepherd(Dog):
def __init__(self, name, age, training_level):
super().__init__(name, age)
self.training_level = training_level
ここで、GermanShepherd
は Dog
のサブクラスです。Dog
クラスから name
と age
属性を継承し、新しい属性 training_level
を追加しています。
-
次に、isinstance()
と type()
関数を使用するコードを追加しましょう。type_check.py
の末尾に以下のコードを追加します。
## Create instances of the Dog and GermanShepherd classes
buddy = Dog("Buddy", 9)
sparky = GermanShepherd("Sparky", 3, "Advanced")
## Check types using isinstance()
print(f"buddy isinstance Dog: {isinstance(buddy, Dog)}")
print(f"sparky isinstance Dog: {isinstance(sparky, Dog)}")
print(f"sparky isinstance GermanShepherd: {isinstance(sparky, GermanShepherd)}")
## Check types using type()
print(f"type(buddy) == Dog: {type(buddy) == Dog}")
print(f"type(sparky) == Dog: {type(sparky) == Dog}")
print(f"type(sparky) == GermanShepherd: {type(sparky) == GermanShepherd}")
この部分では、Dog
クラスのインスタンス (buddy
) と GermanShepherd
クラスのインスタンス (sparky
) を作成しています。その後、isinstance()
と type()
を使ってそれらの型をチェックしています。
-
type_check.py
スクリプトを実行するには、VS Code でターミナルを開き、以下のコマンドを実行します。
python type_check.py
以下の出力が表示されるはずです。
buddy isinstance Dog: True
sparky isinstance Dog: True
sparky isinstance GermanShepherd: True
type(buddy) == Dog: True
type(sparky) == Dog: False
type(sparky) == GermanShepherd: True
この出力は、isinstance(sparky, Dog)
が True
を返すのは、sparky
が Dog
のサブクラスである GermanShepherd
クラスのインスタンスであるからです。しかし、type(sparky) == Dog
は False
を返します。なぜなら type(sparky)
は正確な型である GermanShepherd
を返し、Dog
ではないからです。