-
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를 반환하지 않기 때문입니다.