[python]class(3)

전상욱·2021년 4월 20일
0

Python

목록 보기
12/14

클래스 상속

상속은 말그대로 물려받는다. 즉, 물려받은 기능을 유지한 채로 다른 기능을 추가할 때 사용하는 기능입니다. 물려주는 클래스 : base class / 상속받는 클래스 : derived class
특히) 연관되면서 동등한 기능일 때 사용된다.

  • 클래스 관계 (상속/포함)

상속
상속은 명환하게 같은 종류이며 동등한 관계일 때 사용된다. 즉 , 학생은 사람이다 라는 말이 되면 동등한 관계라 할 수 있다.

class Person:
	def greeting(self):
    	print('hi')
class Student(Person):
	def study(self):
    	print('studying')

포함
예제는 예측하기 쉽게 personlist / person 으로 되어있다. 여기서 상속을 사용하지 않고 포함시키고 있다. PersonList와 사람 Person 은 동등한 관계가 아니라 포함 관계입니다. 즉, 사람목록은 사람을 가지고 있다 ( PersonList has a Person)

정리)같은 종류에 동등한 관계일 때는 상속을 사용하고 그 이외에는 속성에 인스턴스를 넣는 포함 방식을 사용하면 됩니다.

class Person:
    def greeting(self):
        print('hi')
    
class PersonalList:
    def __init__(self):
        self.person_list : [] 

        def append_person(self, person):
            self.person_list.append(person)

base clasa 속성
부모클래스 base class 라고 하는 인스턴스 속성을 사용해보겠습니다. super()로 기반 클래스 초기화를 진행해야한다.
super() 과 같이 부모글래서의 init을 호출해주면 기반 클래스가 초기화되어서 속성이 만들어진다.

class Person:
    def __init__(self):
        print('Person __init__')
        self.hello = '할루'

class Student(Person):
    def __init__(self):
        print('Studnet __init__')
        super().__init__() # super()로 기반 클래스의 __init__ 메서드 호출
        # super(Student, self).__init__()
        self.school = 'zzz'

sam = Student()
print(sam.school)
print(sam.hello)

메서드 오버라이딩
오버라이딩(overriding)은 기반 클래스의 메서드를 무시하고 새로운 메서드를 만드는 뜻입니다. 왜 사용할까? 이유는 보통 프로그램에서 어떤기능이 같은 메서드 이름으로 계속 사용 되어야 할 때 메서드 오버라이딩을 활용합니다.

class Person:
    def greeting(self):
        print('hello')
class Student(Person):
    def greeting(self):
        super().greeting()
        print('my name is rockjeon')

sam = Student()
sam.greeting()
profile
someone's opinion of you does not have to become your reality

0개의 댓글