kakao Cloud school 2기 D+5

LEE EUI JOO·2022년 11월 6일
0
post-thumbnail

배운 내용 (Class , Inherit, Multi - Inherit, Method Overriding)

Class - 객체지향 프로그래밍의 핵심, 사용자 정의 함수, 변수들을 모아서 하나의 객체로 관리하기

#클래스 예제
#게임 캐릭터 클래스 
#속성 : name(이름), score(점수), power(공격력)  
#동작 : __init__
    # live : 점수가 0이면 die, 점수가 0이상이면 alive    -> def로 선언
    # damage : 캐릭터의 점수가 0보다 큰 상태에서 파라미터로 power 전달 받아서 점수 - power 계산
    # __str__ : 계산 결과를 문자열로 출력해 주는 메서드
# ch1, ch2


class Ch:
    name = ''
    score = 0
    power = 0
    
    def __init__(self,name,score,power):
        self.name = name
        self.score = score
        self.power = power
    
    def live(self):
        statement = ''
        if self.score >0 :
            statement = True
        else :
            statement = False
        return statement
    # 캐릭터가 살아 있으면 공격 캐릭터의 공격력 만큼 체력 감소
    # 이미 캐릭터가 죽었으면 죽었다는 메시지 출력
    # 남은 체력보다 공격력이 더 크면 체력은 0
    
    def damage(self,attack):
       if self.live():
           self.score = self.score - attack     
       else:
           print('{}는 이미 die'.format(self.name))
    
    def other(self,other_ch):
        #캐릭터가 살아 있으면 다른 캐릭터의 체력을 자신의 공격력 만큼 감소
        if self.live():
            other_ch.damage(self.power)
    
    def __str__(self) :
        return '{}님의 score는 {}, 공격력은 {}입니다'.format(self.name,self.score,self.power)
    
    
#인스턴스 생성
ch1= Ch('이의주',100,100)
ch2= Ch('홍길동',200,50)

print(ch1)
print(ch2)

ch2.other(ch1)
print(ch2)

클래스(class)는 틀이고 객체(object) or 인스턴스(instance)는 틀에 의해서 실체화 된것 이고, 클래스에 의해서 만들어짐

# 삼각김밥 클래스
class Samgak:
    def __init__(self):
        self.source = '기본 소스'
        self.kim = '광O 김'
        self.bab = '쌀밥'
        self.food = ''
 
    def set_source(self, source_name):
        self.source = source_name
 
    def change_kim(self, kim_name):
        self.kim = kim_name
 
    def change_bab(self, bab_name):
        self.bab = bab_name
 
    def set_food(self, food_name):
        self.food = food_name
 
    def print(self):
        s1 = 'BlockDMask 가 맛있는 삼각김밥을 만들었습니다.\n'
        s1 += f'김은 {self.kim} 입니다.\n'
        s1 += f'밥은 {self.bab} 사용 하였고\n'
        s1 += f'소스는 {self.source} 촵촵 뿌리고\n'
        s1 += f'메인은 {self.food}을 넣었습니다.\n'
        print(s1)
 
 
# 참치 삼각 김밥
chamchi = Samgak()
chamchi.set_food('동O참취')
chamchi.set_source('마요네즈')
chamchi.print()
 
# 매운 김치 삼각 김밥
kimchi = Samgak()
kimchi.set_food('김치')
kimchi.set_source('매운소스')
kimchi.print()
 
# 멸치 삼각 김밥
mulchi = Samgak()
mulchi.change_kim('조O 김')
mulchi.set_food('멸치')
mulchi.print()

클래스에서 가장 중여한 것은 '생성자'

클래스가 객체를 생성할 때 가장 먼저 접근 하는 곳이 생성자임!
init : 클래스의 생성자 , 초기자라고 하며 클래스가 객체를 생성할 때 처음으로 접근하는 곳

즉, 인스턴스를 생성할때 맨 처음으로 초기화를 해주는 작업을 여기서 하면됨!

class Car:
    	def __init__(self):
            print('자동차 불림')
    
car = Car()

인스턴스 car 만 생성했는데 init함수에 의해 불리는 것을 볼 수 있음.

메서드 - 클래스 내부의 함수!

class BananaPhone:
    phone_name = '어른폰'
 
    def __init__(self, number, owner):
        self.number = number
        self.owner = owner
 
    def print(self):
        s = f'이 폰은 {self.phone_name} 기종이며\n'
        s += f'번호는 {self.number} 이고\n'
        s += f'이 폰의 주인은 {self.owner} 입니다.\n'
        print(s)
 
 
# 객체, 인스턴스 생성
p1 = BananaPhone('010-1111-2222', '개님')
p2 = BananaPhone('010-7777-0000', '고양이님')
 
p1.print()
p2.print()

클래스 상속

# 부모 클래스
class Phone:
    phone_name = '피쳐폰'
 
    def __init__(self, my_number, my_name):
        print('Phone 생성자 호출')
        self.my_number = my_number
        self.my_name = my_name
 
    def call(self, number):
        print(f'Phone 전화걸기 : {number}')
 
    def send_msg(self, number, msg):
        print(f'Phone 메시지 보내기 : {number}, {msg}')
 
    def get_info(self):
        print(f'Phone 내 번호 : {self.my_number}')
        print(f'Phone 내 이름 : {self.my_name}')
 
 
# 자식 클래스 1 : 사과폰
class ApplePhone(Phone):
    def __init__(self, my_number, my_name,):
        super(ApplePhone, self).__init__(my_number, my_name)  # 부모 클래스 생성자 호출
        print('ApplePhone 생성자 호출')
 
    def button_home(self):
        print('ApplePhone 홈 버튼 눌림')
 
 
# 자식 클래스 2 : 우주폰
class GalaxyPhone(Phone):
    def __init__(self, my_number, my_name):
        super(GalaxyPhone, self).__init__(my_number, my_name)  # 부모 클래스 생성자 호출
        print('GalaxyPhone 생성자 호출')
 
    def button_cancel(self):
        print('GalaxyPhone 취소(뒤로가기) 버튼이 눌렸습니다')
 
 
# 클래스 생성
print('\n1. 각 클래스의 객체 생성')
phone = Phone('010-2222-2222', '폰은정')
apple = ApplePhone('010-1234-5678', '김멸치')
galaxy = GalaxyPhone('010-4321-4321', '김근육')
 
# 부모 클래스로 부터 물려받은 메서드
print('\n2. 부모 클래스의 메서드 호출')
phone.get_info()
apple.get_info()
galaxy.get_info()
apple.call('010-0000-0000')
apple.send_msg('010-0000-1234','안녕')
galaxy.call('010-1234-124')
galaxy.send_msg('010-1234-1234','hi')
 
# 본인 메서드
print('\n3. 자식 클래스의 메서드 호출')
apple.button_home()
galaxy.button_cancel()

모양 - 자식 클래스 (부모클래스):

자식 클래스 생성자에서 부모클래스의 생성자를 불러주는 방법 - super(자식클래스,self).init(부모클래스 생성자 매개변수)

메서드 오버라이딩

부모 클래스에 있는 메서드를 덮어 씌우는것

메서드를 자식클래스에서 재정의 하면, 자식 클래스에서 해당 메서드로 호출했을 때 부모클래스의 메서드는 가려지고 재정의한 자식클래스의 메서드가 호출된다.

# 처리조건
# 그림과 같이 부모클래스 Pen에 대한 자식 클래스 세개를 만들고, Pencil 과 Ballpen 클래스는 writeLetter 를 오버라이드 하고 
# Fountainpen 클래스는 오버라이드 하지 않는다. 객체 생성 후 다형성을 사용해 결과를 출력한다

# Pen 클래스의 writeLetter 메서드의 내용은 다음과 같다.
#         def writeLetter(self):
#             print('글씨를 쓴다')
class Pen:
    def __init__(self):
        pass
    def writeLetter(self):
        print('글씨를 쓴다')


class Pencil(Pen):
 
    def writeLetter(self): # 메서드 오버라이딩
        print('연필이 최고')
   

class Ballpen(Pen):

    def writeLetter(self): #메서드 오버라이딩
        print('볼펜이 최고')


class Fountainpen(Pen):
    pass
    
pencil = Pencil()
ballpen = Ballpen()
fountainpen = Fountainpen() #메소드 오버라이딩 하지 않음!

pencil.writeLetter()
ballpen.writeLetter()
fountainpen.writeLetter()

다중 상속 - Multi - inherit

class Doonkey:
    data = '당나귀 최고'
    
    def skill(self):
        print('당나귀 : 짐나르기')
        
class Horse:
    def skill(self):
        print('말 : 달리기')
    def hobby(self):
        print('말은 달리기가 취미')
        
class Mule1(Horse,Doonkey): #호출 순서 유의 skill 메서드가 중복되나 가장 이른 순서가 호출된다.
    pass

mu1= Mule1()
print(mu1.data)
mu1.skill()
mu1.hobby()

class Mule2(Horse,Doonkey):
    def play(self):
        print('노새 고유 메서드')
        
    def hobby(self):
        print('노새는 걷기를 즐김')
    def showhobby(self):
        self.hobby()
        super().hobby()
        
    def showdata(self):
        print(self.data)
        print(super().data)
        
mu2 = Mule2()
mu2.skill()
mu2.hobby()
mu2.play()
mu2.showhobby()
mu2.showdata()

참조 - 개발자 지망생님 블로그

profile
무럭무럭 자라볼까

0개의 댓글