본문 바로가기
파이썬

💾 상속, 캡슐화, 다형성

by Ele(단단) 2021. 6. 27.
반응형

📥 상속 : 부모 클래스의 모든 것을 자식 클래스에게 물려주는 것

목적 : 한 번 정의한 데이터 타입을 필요에 따라서 수정을 하고 다시 재활용해서 반복되는 코드를 줄이고자 하는 것

class Animal():
  species = '모르는 동물'
    
  def say(self):
    print(self.species + '입니다.')
        
# Animal이라는 클래스 생성

class Dog(Animal):
    species = '강아지'    
    
class Cat(Animal):
    species = '고양이'

#Animal클래스를 상속받는 Dog, Cat클래스 생성

dog = Dog()
cat = Cat()
# dog, cat 인스턴스 생성(클래스의 의해 만들어진 객체)

dog.say()
cat.say()
# 강아지입니다. //출력
# 고양이입니다. //출력

오버라이딩 : 부모 클래스에서 정의한 메소드를 자식 클래스에서 변경하는 것

컴포지션 : 자식클래스가 필요한 속성만 부모클래스로부터 가져와 사용하는 것

class Find:
    def __init__(self, number):
        self.number = number

    def two(self):
        return self.number % 2

    def five(self):
        return self.number % 5
        
class FindFive:
    def __init__(self, number):
        self.number = number
        self.find_five = Find(number)
        
    def five(self):
        return self.find_five.five()

# self.find_five = Find(number)로 Find클래스 인스턴스를 생성
# FindFive 클래스 내부에 five라는 메서드 생성
# 리턴 값으로 초기에 생성한 인스턴스인 self.find_five 변수를 사용하여 Find의 five메서드를 사용

💊 캡슐화 : 클래스 내 존재하는 멤버 변수를 클래스 내 메서드를 통해서만 설정하고 반환할 수 있게 하는 것

목적 : 가지고 있는 데이터를 바깥에서 은닉하고 일부 함수만 바깥에 노출함으로써 데이터 접근을 관리하는 것

class Human:
    def __init__(self, name, birthday):
        self.__set(name, birthday)
        
    def __set(self, name, birthday):
        self.__name = name
        self.__birthday = birthday
    
    def get_name(self):
        return self.__name
    
    def get_birthday(self):
        return self.__birthday
        
# '__이름' 언더바 2개로 데이터 은닉을 한다

 Ele = Human('Ele', '0701')
 
 print(Ele.__name) or print(Ele.name) # 오류 난다, 캡슐화를 했기 때문에
 print(Ele.__birthday) or print(Ele.birthday) # 오류 난다, 캡슐화를 했기 때문에
 
print(test.get_name()) # Ele // 출력
print(test.get_birthday()) # 0701 // 출력
 
# 일반적으로 set/get 함수를 생성하여 캡슐화된 데이터로 가져온다

다형성 : 동일한 모양의 코드가 다른 동작을 하는 것

class Animal():
    species = '모르는 동물'
    
    def say(self):
        print(self.species + '입니다.')
        
# Animal이라는 클래스 생성

class Dog(Animal):
    species = '강아지'    
    
class Cat(Animal):
    species = '고양이'

#Animal클래스를 상속받는 Dog, Cat클래스 생성

dog = Dog() # <= 다형성
cat = Cat() # <= 다형성

dog.say()
cat.say()
# 강아지입니다. //출력
# 고양이입니다. //출력
반응형

댓글