1. 클래스와 객체
클래스란 객체를 정의하는 틀 또는 설계도
객체란 설계도로부터 만들어낸 제품
클래스를 기반으로 만들어진 객체를 인스턴스라고 부른다
클래스에는 객체의 모든 속성과 메서드가 정의되어 있다.
메서드란 클래스가 가지고 있는 함수이다.
클래스 만들기
class 클래스 이름:
def 메서드 이름(self):
명령 블록
호출하기
인스턴스(변수 이름)=클래스이름()
인스턴스.메서드()
class Monster:
def say(self):
print("나는 몬스터다!")
goblin=Monster()
goblin.say()
2. 생성자
생성자란 클래스 이름과 같은 함수를 말한다
클래스 내부에 __init__라는 함수를 만들면 객체를 생성할 때 처리할 내용을 작성할 수 있다.
인스턴스를 만들때 반드시 호출되는 메서드 -> __init__
속성 추가하기
class Monster:
def __init__(self, health, attack, speed): # self: 자기자신을 나타내는 인스턴스
self.health = health
self.attack = attack
self.speed = speed
goblin = Monster(800, 120, 300) #순서대로 health,attack, speed의 매개변수로 들어감
wolf = Monster(1500, 200, 350)
메서드 추가하기
class Monster:
def __init__(self, health, attack, speed):
self.health = health
self.attack = attack
self.speed = speed
def decrease_health(self, num): #체력 감소하기
self.health -= num
def get_health(self): #체력 가져오
return self.health
goblin = Monster(800, 120, 300)
goblin.decrease_health(100) #메서드 호출
print(goblin.get_health())
#생성자
#:인스턴스를 만들 때 호출되는 메서드
class Monster:
def __init__(self,health,attack,speed):
self.health=health #현재 호출하고 있는 인스턴스의 health 변수에 값을 대입
self.attack=attack
self.speed=speed
def decrease_health(self,num):
self.health-=num
def get_health(self):
return self.health
#고블린 인스턴스 생성
goblin=Monster(800,120,300)
goblin.decrease_health(100)
print(goblin.get_health())
#늑대 인스턴스 생성
wolf=Monster(1500,200,350)
wolf.decrease_health(1000)
print(wolf.get_health())
#파이썬에서는 자료형도 클래스다
3. 상속
부모 클래스에 있는 속성과 메서드를 자식 클래스가 그대로 가지고 올 수 있는 것을 상속이라고 한다.
부모클래스 정의
class Monster:
def __init__(self, name, health, attack): #속성: 1.이름 2.체력 3.공격력
self.name = name
self.health = health
self.attack = attack
def move(self): #메서드: 이동하기
print("지상에서 이동하기")
자식클래스 정의
class Wolf(Monster): # 몬스터 클래스 상속받음
pass
class Shark(Monster): #메서드 오버라이딩: 메서드의 재정의
def move(self):
print("헤엄치기")
class Dragon(Monster):
def move(self):
print("날기")
#상속
#클래스들에 중복된 코드를 제거하고 유지보수를 편하게 하기위해서 사용
#부모 클래스
class Monster:
def __init__(self,name,health,attack):
self.name=name
self.health=health
self.attack=attack
def move(self):
print(f"[{self.name}] 지상에서 이동하기")
#자식 클래스
class Wolf(Monster): #몬스터 상속받음
pass
class Shark(Monster):
def move(self):
print(f"[{self.name}] 헤엄치기") #메서드 오버라이딩:메서드 재정의
class Dragon(Monster):
def move(self): #메서드 오버라이딩
print(f"[{self.name}] 날기")
wolf=Wolf("울프",1500,200)
wolf.move()
shark=Shark("샤크",3000,400)
shark.move()
dragon=Dragon("드래곤",8000,800)
dragon.move()
4. 오버라이딩, 클래스변수
오버라이딩이란 상속 관계에 있는 부모 클래스에서 이미 정의된 메소드를 자식 클래스에서 같은 시그니쳐를 갖는 메소드로 다시 정의
클래스 변수란 인스턴스들이 모두 공유하는 변수를 말한다
드래곤 클래스에 인스턴스 속성으로 3개의 스킬을 추가
드래곤이 스킬을 쓰면 속성 중에 하나가 무작위로 사용된다
오버라이딩
class Dragon(Monster):
클래스 변수
class Monster:
max_num=1000
def __init__(self,name,health,attack):
self.name=name
self.health=health
self.attack=attack
Monster.max_num-=1 #클래스 변수를 사용할 때는 self를 쓰지 않는다
#오버라이딩
#부모 클래스
# 클래스 변수
# 인스턴스들이 모두 공유하는 변수
import random
class Monster:
max_num=1000
def __init__(self,name,health,attack):
self.name=name
self.health=health
self.attack=attack
Monster.max_num-=1
def move(self):
print(f"[{self.name}] 지상에서 이동하기")
#자식 클래스
class Wolf(Monster): #몬스터 상속받음
pass
class Shark(Monster):
def move(self):
print(f"[{self.name}] 헤엄치기") #메서드 오버라이딩:메서드 재정의
class Dragon(Monster):
#생성자 오버라이딩
def __init__(self,name,health,attack):
super().__init__(name,health,attack) #부모 생성자 불러오기
self.skills=("불뿜기","꼬리치기","날개치기") #튜플 사용
def move(self): #메서드 오버라이딩
print(f"[{self.name}] 날기")
def skill(self):
print(f"[{self.name}] 스킬 사용 {self.skills[random.randint(0,2)]}")
wolf=Wolf("울프",1500,200)
wolf.move()
print(wolf.max_num)
shark=Shark("샤크",3000,400)
shark.move()
print(shark.max_num)
dragon=Dragon("드래곤",8000,800)
dragon.move()
dragon.skill()
print(dragon.max_num)
실습정리
아이템 공통 : 이름, 가격, 무게, 판매하기, 버리기
장비 아이템 : 착용효과, 착용하기
소모품 아이템 : 사용효과, 사용하기
(단, 버리기는 버릴 수 있는 아이템만 가능하다)
#실습
#아이템 공통:이름 가격 무게 판매하기 버리기
#장비아이템: 착용효과 착용하기
#소모품 아이템: 사용효과,사용하기
class Item:
def __init__(self,name,price,weight,isdropable):
self.name=name
self.price=price
self.weight=weight
self.isdropable=isdropable
def sale(self):
print(f"[{self.name}]의 판매가격은 [{self.price}]")
def discard(self):
if self.isdropable:
print(f"[{self.name}]을 버렸습니다")
else:
print(f"[{self.name}]을 버릴 수 없습니다")
class WearableItem(Item):
def __init__(self, name ,price, weight, isdropable, effect):
super().__init__(name,price,weight,isdropable) #오버라이딩
self.effect=effect
def wear(self):
print(f"[{self.name}]착용했습니다. {self.effect}")
class UsableItem(Item):
def __init__(self, name ,price, weight, isdropable, effect):
super().__init__(name,price,weight,isdropable)
self.effect=effect
def use(self):
print(f"[{self.name}] 사용했습니다. {self.effect}가 지속됩니다")
#인스턴스 생성
sword=WearableItem("이가닌자의검", 30000, 3.5, True, "체력 5000증가 마력 5000증가")
sword.wear()
sword.sale()
sword.discard()
potion=UsableItem("신비한투명물약",150000,0.1,False,"투명효과 300초 지속")
potion.discard()
potion.sale()
potion.use()
실행결과

'💻 Programming > Python' 카테고리의 다른 글
[Python] 파이썬 슬라이싱 정리 (0) | 2025.04.18 |
---|---|
[Python] csv 파일 입출력 (0) | 2023.01.22 |
[Python] 파일 입출력 기본 (0) | 2023.01.22 |
[Python] 과제 10주차 (0) | 2023.01.08 |
[Python] 과제 9주차 (0) | 2023.01.08 |