상속

hyunsooo·2021년 8월 1일
0

클래스 상속

상속은 말 그대로 자신이 가지고 있는것을 물려주는 개념이다.
부모 클래스(parent class, base class, super class)가 기반이 되고 물려받는 클래스를 자식 클래스(child class, derived class, sub class)라고 부른다.

class parent_class:
    def __init__(self):
        self.name = 'hyunsoo'
        self.birthday = 930415

    def p_print(self):
        print(f"내이름은 {self.name}입니다.")

class child_class(parent_class):
    def __init__(self):
        super(child_class,self).__init__()
        self.myname ='hyosung'
        self.mybirthday=930111

child = child_class()
print(f"내 이름은 {child.myname}이고 내친구 {child.name}의 생일은 {child.birthday}이다")
child.p_print()

super(classname,self).init() : classname에 해당하는 class의 부모를 상속받으라는 느낌
super(classname,self).init(**kwargs) : 부모클래스에 init인자로 argument들이 있을때 사용하는 문법

python3.x 버전에서는 super().init()처럼 사용할 수 있지만 위의 2.x버전도 호환이 되기 때문에 위 문법으로 사용해주는게 범용성이 좋다.

overriding

클래스의 상속 시, 부모클래스에서 정의한 메소드를 자식 클래스에서 변경하는것을 말한다.

class parent_class:
    def __init__(self):
        self.name = "hyunsoo"

    def birth_d(self,day):
        print(f"{self.name}의 생일은 {day}이다")

class child_class(parent_class):
    def __init__(self):
        super(child_class,self).__init__()
        self.myname = "taewoo"

    def birth_d(self,day):
        print(f"{self.myname}의 생일은 {day}이다")

child = child_class()
child.birth_d(930111)
print(child.name)

overloading

메소드의 함수명이 같지만 전달받는 argument들의 차이에 의해 메소드를 다르게 호출하는 경우
파이썬에는 오버로딩을 지원하지 않고 한 클래스내에서 같은 메소드명이 존재하면, 맨 마지막으로 정의된 메소드가 작동한다. 하지만 다른 언어에서는 자주 사용하는 용어이니 알아두면 좋다.

profile
CS | ML | DL

0개의 댓글