본문 바로가기
개발일지/Python

Python class3 - 상속

by 개발에정착하고싶다 2022. 9. 28.
320x100
# 클래스 상속

class Person():
    
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name
        
    def hello(self):
        print('hello')

    def report(self):
        print(f'I am {self.first_name} {self.last_name}')

x = Person('John', 'Smith')
x.hello()
# hello
x.report()
# I am John Smith


class Agent(Person):

    # 상속받은 report를 그대로 사용하지 않고 변형하고 싶을때
    # 이런 '오버라이드'를 하면 된다.
    def report(self):
        print('I am here.')
    
    def reveal(self, passcode):
        if passcode == 123:
            print('I am a secret agent!')
        else:
            self.report()

x = Agent('John', 'smith')
# 상속받은 클래스를 쓸때는 상속받은 클래스 내부에 있는 메서드는 사용이 안되는것같다.
# 상속해준 클래스 안의 메서드를 사용해야하는 것 같다.
x.reveal(123)
# I am a secret agent!
300x250