TIL(16일차)

김규현·2022년 9월 21일
0

클래스 상속

클래스에서 부모 클래스로 부터 상속을 받을 수 있다.
자식 클래스에서 부모 클래스의 init 함수 안에 있는 속성을 가져오려면
super().init()을 이용해서 가져올 수 있다.

class Animal:
    def __init__(self):
        print("Animal created")

    def whoAmI(self):
        print("Animal")

    def eat(self):
        print("Eating")


class Dog(Animal):
    def __init__(self):
        super().__init__()
        print("Dog created")

    def whoAmI(self):
        print("Dog")

    def bark(self):
        print("Woof!")


class Cat(Animal):
    def __init__(self):
        super().__init__()
        print("Cat created")

    def whoAmI(self):
        print("Meow!")


dog = Dog()
cat = Cat()
dog.whoAmI()
cat.whoAmI()

출력 순서
1. dog 인스턴스가 실행되고 Dog 클래스 호출되어 init 메서드가 자동으로 실행
(init메서드에서 super().init()이 있기 때문에 부모 클래스의 init 메서드로 넘어가서 "Animal created"가 출력된 다음 다시 Dog 클래스로 넘어와서 "Dog created"가 출력된다.)

2. cat 인스턴스 역시 dog와 같이 cat 인스턴스 실행 후 Cat 클래스가 호출되어 init이 실행되고 부모 클래스에서 init 메서드를 상속받아 실행한 다음 다시 Cat 클래스로 내려와 "Cat created" 출력
3. dog.whoAmI()는 dog 인스턴스의 whoAmI 메서드를 실행하고 해당 메서드의 속성인 "Dog"가 출력된다.
4. cat.whoAmI()역시 dog.whoAmI()와 동일하게 실행되어 "Meow!"가 출력된다.

📌init 함수 외에도 특별 함수가 존재하며 __ str __ ,__ len __ , __del __ 등이 있다.

  • __ str__ : 결과 값을 문자로 나타내는 특별함수
  • __len__ : 결과 값을 길이로 나타내는 특별함수
  • __del__ : 지정한 값을 지워주는 특별함수
class Book:
    def __init__(self, title, author, pages):
        print("A book is created")
        self.title = title
        self.author = author
        self.pages = pages

    def __str__(self):
        return f"{self.title}, {self.author}, {self.pages}"

    def __len__(self):
        return self.pages

    def __del__(self):
        print("A book is destroyed")


book = Book("Python Rocks!", "권기현", 159)

print(len(book))
profile
웹개발 회고록

0개의 댓글