[python] class 상속

Song A·2024년 6월 17일

클래스란?

객체를 만들기 위한 속성과 기능을 설정
'객체 생성자 호출'을 통해 클래스는 하나여도 여러 객체 생성 가능
(클래스는 '부품 틀', 객체는 '부품')

class 키워드, 속성(변수), 기능(함수)

클래스 상속

다른 클래스의 기능을 가져와서 사용하는 것
클래스는 또 다른 클래스를 상속해서 내 것처럼 사용할 수 있다.

class1 : A 기능
class2 : B 기능
class3 : C 기능
만약 class2가 class1 상속, class3이 class2 상속했다면,
class1 : A 기능
class2 : A 기능, B 기능
class3 : A 기능, B 기능, C 기능

class TurboCar(Normal): # Norml 클래스 상속
    def turbo(self):
        print("turbo")

생성자

객체가 생성될 때 생성자를 호출하면 __init__()가 자동 호출된다.
속성 초기화
상속 관계일 때 super() 메소드 사용해 상위 클래스의 속성 초기화

cal = Cal()
Cal() 생성자 호출
Cal() __init__() 호출

class Cal2(Cal): # 상속시 기능은 받아 올 수 있으나, 속성은 받아오지 못함
    def __init__(self, n1, n2): # 따로 속성을 강제로 호출해 줘야 함
        self.n1 = n1
        self.n2 = n2
        print("init 호출222")

        Cal.__init__(self, n1, n2) # 방법 1
        super().__init__(n1, n2) # 방법 2

다중 상속

2개 이상의 클래스를 상속한다.
너무 남발하면 안됨-> 코드가 헷갈릴 수 있음.

class Cal2(Cal,Cal1, Cal2)

오버라이딩

메서드 재정의
하위 클래스에서 상위 클래스의 메서드 재정의

class TriArea:
    def __init__(self, w, h):
        self.height =h
        self.weight =w

    def getArea(self):
        return self.weight *self.weight

class NewTriArea(TriArea):
    def __init__(self,w,h):
        super().__init__(w,h)

    def getArea(self):
        return str(super().getArea())+'cm2'

중복제거, 효율적으로 관리 가능

추상 클래스

메서드 구현을 강요 / 상위 클래스가 구현되지 않은 메서드를 가지고 있다.
상위 클래스가 하위 클래스에세 메서드 구현을 강요한다.
특정 기능 상속시 입맛에 맞게 기능 변경해서 사용할 수 있다.

from abc import ABCMeta
from abc import abstractmethod
class 클래스명(metaclass=ABCMeta):
(들여쓰기)@abstractmethod
(들여쓰기)def 함수명(self):

from abc import ABCMeta
from abc import abstractmethod

class AirPlane(metaclass=ABCMeta):
    @abstractmethod
    def flight(self):
        pass

    def start(self):
        print("전진")
    
class Airliner(AirPlane):
    def __init__(self,c):
        self.color = c

    def flight(self):
        print("추상 클래스")

? : 추상 클래스 사용시 변수 갯수를 맞춰야만 하나? -> 테스트 시 상관 없이 돌아감?

profile
진행중

0개의 댓글