본문 바로가기
코딩(개발)/파이썬

파이썬 class

by 플랜데버 2020. 12. 21.

 

공부하는게 취미인 사람들 투딩


객체지향: 객체들의 상호작용으로 서술 하는 방식 

 

#객체 : 메소드와 변수의 묶음

#클래스 : 하나 이상의 유사한 객체들을 묶어 공통된 특성을 표현한 데이터 추상화 (붕어빵틀)

#인스턴스 : 클래스로 부터 만들어진 것 (붕어빵)

 

코드
class Unit:
    def __init__(self,name,hp,damage) :
        self.name = name 
        self.hp = hp
        self.damage = damage
        print("{0} 유닛이 생성되었습니다.".format(self.name))  ①
        print("체력 {0} , 공격력 {1}\n".format(self.hp,self.damage))  ①

marine1 = Unit("마린" , 20 ,25)       
marine2 = Unit("마린" , 10 , 55) 
tank = Unit("탱크" , 160 , 35)  

멤버변수 : 클래스내에서 정의된 변수 :self.name , self.hp , self.damage

 

#외부에서 멤버변수 호출하기

코드
wraith1 = Unit("레이스",80,5)
print("유닛이름 : {0} , 공격력 : {1}" .format(wraith1.name, wraith1.damage))

 

 

#메소드

코드

#클래스 정의
class
 AttackUnit:

    def __init__(self,name,hp,damage) :

        self.name = name

        self.hp = hp

        self.damage = damage

        

    def attack(self,location) :

        print("{0} 유닛이: {1} 방향으로 적군을 공격합니다.[공격력 {2}]".format(self.name,location,self.damage))

        

    def damaged(self,damage) :

        print("{0} 유닛이: {1} 데미지를 입었습니다.".format(self.name,damage))

        self.hp -= damage

        print("{0} 유닛의 현재 체력은 {1} 입니다.".format(self.name,self.hp))

        if self.hp <= 0 :

            print("{0} : 파괴 되었습니다." .format(self.name))



#클래스 호출

firebat1 = AttackUnit("파이어뱃" , 50 ,16)        

firebat1.attack("5시")

 

#공격 두번 받는다고 가정

firebat1.damaged(25)

firebat1.damaged(25)

 

결과

파이어뱃 유닛이: 5시 방향으로 적군을 공격합니다.[공격력 16]
파이어뱃 유닛이: 25 데미지를 입었습니다.
파이어뱃 유닛의 현재 체력은 25 입니다.  
파이어뱃 유닛이: 25 데미지를 입었습니다.
파이어뱃 유닛의 현재 체력은 0 입니다.   
파이어뱃 : 파괴 되었습니다.

 

 

 

#상속    

코드

#일반유닛

class Unit

    def __init__(self,name,hp) :

        self.name = name

        self.hp = hp

       

#공격유닛

class AttackUnit(Unit): 

    def __init__(self,name,hp,damage) :

        Unit.__init__(self,name,hp)

        self.damage = damage

 

    def attack(self,location) :

        print("{0} 유닛이: {1} 방향으로 적군을 공격합니다.[공격력 {2}]".format(self.name,location,self.damage))

        

    def damaged(self,damage) :

        print("{0} 유닛이: {1} 데미지를 입었습니다.".format(self.name,damage))

        self.hp -= damage

        print("{0} 유닛의 현재 체력은 {1} 입니다.".format(self.name,self.hp))

        if self.hp <= 0 :

            print("{0} : 파괴 되었습니다." .format(self.name))



#파이어뱃 : 공격 유닛 , 화염방사기

firebat1 = AttackUnit("파이어뱃" , 50 ,16)        #공격

firebat1.attack("5시")

 

#공격 두번 받는다고 가정

firebat1.damaged(25)

firebat1.damaged(25)  

①Unit 클래스를 상속받겠다.

 

결과    

파이어뱃 유닛이: 5시 방향으로 적군을 공격합니다.[공격력 16] 
파이어뱃 유닛이: 25 데미지를 입었습니다. 
파이어뱃 유닛의 현재 체력은 25 입니다.   
파이어뱃 유닛이: 25 데미지를 입었습니다. 
파이어뱃 유닛의 현재 체력은 0 입니다.    
파이어뱃 : 파괴 되었습니다.

 

 

#다중상속

코드

# #일반유닛
class Unit:
    def __init__(self,name,hp) :
        self.name = name
        self.hp = hp

#공격유닛 
class AttackUnit(Unit):
    def __init__(self,name,hp,damage) :
        Unit.__init__(self,name,hp)
        self.damage = damage

# 날 수 있는 기능을 가진 클래스
class Flyable:
    def __init__(self,flying_speed) :
         self.flying_speed = flying_speed
 
    def fly(self,name, location) :
        print("{0} 유닛이: {1} 방향으로 날아갑니다. [속도 {2}]".format(name, location , self.flying_speed))

# 공중 공격 유닛 클래스
class FlyableAttackUnit(AttackUnit,Flyable):
    def __init__(self,name,hp,damage,flying_speed) :
        AttackUnit.__init__(self,name,hp,damage)
        Flyable.__init__(self,flying_speed)
 

valkyrie = FlyableAttackUnit("발키리" ,200 , 6 ,5)        #공격
valkyrie.fly(valkyrie.name, "3시")

 

 

# 메소드 오버라이딩 : 자식 클래스에서 정의한 메소드를 쓰고 싶을때

코드
#일반유닛
class Unit:
    def __init__(self,name,hp,speed) :
        self.name = name
        self.hp = hp
        self.speed = speed

    def move(self, location):
        print("[지상 유닛 이동]")
        print("{0}:{1} 방향으로 이동 합니다. [속도 {2}]".format( self.name, location , self.speed))

#공격유닛 
class AttackUnit(Unit):
    def __init__(self,name,hp, speed, damage) :
        Unit.__init__(self,name,hp , speed)
        self.damage = damage

# 날 수 있는 기능을 가진 클래스
class Flyable:
    def __init__(self,flying_speed) :
         self.flying_speed = flying_speed
 
    def fly(self,name, location) :
        print("{0} 유닛이: {1} 방향으로 날아갑니다. [속도 {2}]".format(name, location , self.flying_speed))

# 공중 공격 유닛 클래스
class FlyableAttackUnit(AttackUnit,Flyable):
    def __init__(self,name,hp,damage, flying_speed) :
        AttackUnit.__init__(self, name, hp, 0 , damage)
        Flyable.__init__(self,flying_speed)
 
    #오버로딩
    def move(self, location):
        print("[공중 유닛 이동]")
        self.fly(self.name, location )

    

#벌쳐 : 지상 유닛, 기동성이 좋음
vulture = AttackUnit("벌쳐" , 80, 10, 20)

#배틀크루져 : 공중 유닛 , 체력도 굉장히 좋음 , 공격력도 좋음
battlecruiser = FlyableAttackUnit("배틀크루저" , 500 , 25, 3)

vulture.move("11시")
# battlecruiser.fly(battlecruiser.name, "9시")
battlecruiser.move("9시")

 

 

#pass

코드

#일반유닛

class Unit:

    def __init__(self,name,hp,speed) :

        self.name = name

        self.hp = hp

        self.speed = speed

 

    def move(self, location):

        print("[지상 유닛 이동]")

        print("{0}:{1} 방향으로 이동 합니다. [속도 {2}]".format( self.name, location , self.speed))

 

class BuildingUnit(Unit):

    def __init__(self, name , hp, location):

        pass   #아무것도 않하고 일단 넘어간다는 뜻

 

supply_depot = BuildingUnit("서플라이 디폿"500"7시")    



#함수에서 사용하기

def game_start():

    print("[알림] 새로운 게임을 시작합니다.")

 

def game_over():

    pass

 

game_start()

game_over()

 

 

 

#super

 

코드

class Unit:

    def __init__(self,name,hp,speed) :

        self.name = name

        self.hp = hp

        self.speed = speed

 

    def move(self, location):

        print("[지상 유닛 이동]")

        print("{0}:{1} 방향으로 이동 합니다. [속도 {2}]".format( self.name, location , self.speed))

 

class BuildingUnit(Unit):

    def __init__(self, name , hp, location):

        #Unit.__init__(self,name , hp,0)

        super().__init__(name , hp,0#위를 얘 처럼 쓸수 있다. 다중상속이 안된다... super 를 사용하면 상속을 한 클래스의 함수를 추가적으로 모두 적어 주지 않고도 사용할 수 있다.

        self.location = location

 

 

# Quiz) 주어진 코드를 활용하여 부동산 프로그램을 작성하시오.

 

# (출력예제)

# 총 3대의 매물이 있습니다.

# 강남 아파트 매매 10억 2010년

# 마포 오피스텔 전세 5억 2007년

# 송파 빌라 월세 500/50 2000년

 

코드

class House:

    #매물 초기화

    def __init__(self, location, house_type , deal_type , price , completion_year):

        self.location = location

        self.house_type = house_type

        self.deal_type = deal_type

        self.price = price

        self.completion_year = completion_year



    #매물 정보 표시

    def show_detail(self):

        print(self.location,self.house_type,self.deal_type,self.price,self.completion_year)

 

#리스트 [] : 순서를 가진 객체의 집합 = 배열

houses = []

house1 = House("강남""아파트" , "매매" , "10억" , "2010년")       

house2 = House("마포""오피스텔" , "전세" , "5억" , "2007년"

house3 = House("송파""빌라" , "월세" , "500/50" , "2000년"

 

houses.append(house1)

houses.append(house2)

houses.append(house3)



print("총 {0}대의 매물이 있습니다.".format(len(houses)))

 

for  houses in houses:

      houses.show_detail()

 



 

 

itwiki.kr/w/%EA%B0%9D%EC%B2%B4%EC%A7%80%ED%96%A5_%EA%B8%B0%EB%B2%95#.EA.B0.9D.EC.B2.B4.28Object.29

 

객체지향 기법 - IT위키

 

itwiki.kr

 

post.naver.com/viewer/post

 

일반 함수와 클래스 함수의 7개 차이점

[BY 안국이] 클래스 함수도 함수의 일종이라는 점을 강조하였지만 사실 적지 않은 차이점들이 있습니다....

m.post.naver.com

 

파이썬 기초는 나도코딩님이 인프런사이트에서 강의한 내용을 바탕으로 공부한 내용을 정리한 것 입니다.

추천 :  ★

 

 

'코딩(개발) > 파이썬' 카테고리의 다른 글

파이썬 모듈 / 패키지  (0) 2020.12.23
파이썬 예외처리  (0) 2020.12.22
파이썬 파일 입출력  (0) 2020.12.20
파이썬 표준 입출력  (0) 2020.12.20
파이썬 함수 문제 풀기  (0) 2020.12.20

댓글