파이썬 - 클래스(부모 클래스의 속성 사용)

정태경·2022년 1월 15일
0

클래스 - 부모클래스의 속성 사용하기

""" 부모 클래스의 속성을 사용하려면 super().__init__() 메서드를 호출해 초기화 해주어야함 """

class Person:
    def __init__(self):
        print('Person __init__')
        self.hello = '안녕하세요.'
 
class Student(Person):
    def __init__(self):
        print('Student __init__')
        super().__init__()                # super()로 기반 클래스의 __init__ 메서드 호출
        self.school = '파이썬 스쿨'
 
james = Student()
print(james.school)
print(james.hello)

""" 예외조건으로 만약 자식 클래스에 __init__ 메서드를 생략하면 부모 클래스의 __init__ 메서드가
    자동으로 호출되기 때문에 super() 호출하지 않아도 됌 """

class Person:
    def __init__(self):
        print('Person __init__')
        self.hello = '안녕하세요.'
 
class Student(Person):
    pass
 
james = Student()
print(james.hello)
profile
現 두나무 업비트 QA 엔지니어, 前 마이리얼트립 TQA 엔지니어

0개의 댓글