Topic 2: 속성과 메서드 - 객체의 특성과 행동 🎭
🎯 학습 목표
클래스에 속성(정보)과 메서드(행동)를 추가하여 객체가 데이터를 저장하고 기능을 수행할 수 있도록 만들 수 있습니다.
🏷️ 속성(Attribute)이란?
객체가 가지는 정보
속성은 객체가 가지고 있는 정보나 특성입니다.
실생활 비유:
- 학생의 속성: 이름, 나이, 학년, 반
- 자동차의 속성: 색깔, 브랜드, 속도, 연료량
- 휴대폰의 속성: 브랜드, 색상, 배터리, 저장용량
간단한 속성 추가하기
class Student:
def __init__(self):
# 속성들 정의
self.name = "kim_cheolsu"
self.age = 16
self.grade = 2
self.class_num = 3
# 학생 객체 생성
student = Student()
# 속성에 접근하기
print(f"이름: {student.name}") # 이름: 김철수
print(f"나이: {student.age}") # 나이: 16
print(f"학년: {student.grade}") # 학년: 2
print(f"반: {student.class_num}") # 반: 3
self란?
self는 객체 자신을 가리키는 특별한 키워드입니다.
class Car:
def __init__(self):
self.brand = "현대" # 이 객체의 브랜드
self.color = "빨강" # 이 객체의 색깔
self.speed = 0 # 이 객체의 속도
# 두 대의 서로 다른 자동차
car1 = Car()
car2 = Car()
print(f"car1 브랜드: {car1.brand}") # 현대
print(f"car2 브랜드: {car2.brand}") # 현대
# 각각 다른 객체지만 같은 초기값을 가짐
🎬 메서드(Method)란?
객체가 할 수 있는 행동
메서드는 객체가 수행할 수 있는 행동이나 기능입니다.
실생활 비유:
- 학생의 행동: 공부하기, 자기소개하기, 시험보기
- 자동차의 행동: 시동걸기, 가속하기, 브레이크 밟기
- 휴대폰의 행동: 전화걸기, 문자보내기, 사진찍기
간단한 메서드 추가하기
class Student:
def __init__(self):
self.name = "kim_cheolsu"
self.age = 16
self.grade = 2
# 메서드: 자기소개하기
def introduce(self):
print(f"안녕하세요! 저는 {self.name}입니다.")
print(f"나이는 {self.age}세이고, {self.grade}학년입니다.")
# 메서드: 공부하기
def study(self):
print(f"{self.name}가 열심히 공부하고 있습니다! 📚")
# 메서드: 운동하기
def exercise(self):
print(f"{self.name}가 운동하고 있습니다! 🏃♂️")
# 학생 객체 생성
student = Student()
# 메서드 호출하기
student.introduce() # 자기소개
student.study() # 공부하기
student.exercise() # 운동하기
🔧 속성 수정하기
속성 값 변경
class Car:
def __init__(self):
self.brand = "현대"
self.color = "흰색"
self.speed = 0
def show_info(self):
print(f"브랜드: {self.brand}")
print(f"색깔: {self.color}")
print(f"현재 속도: {self.speed}km/h")
# 자동차 객체 생성
my_car = Car()
print("=== 초기 상태 ===")
my_car.show_info()
print("\n=== 속성 변경 후 ===")
# 속성 값 변경
my_car.color = "빨강"
my_car.speed = 60
my_car.show_info()
메서드로 속성 변경하기
class Car:
def __init__(self):
self.brand = "현대"
self.color = "흰색"
self.speed = 0
def accelerate(self):
"""가속하기"""
self.speed += 10
print(f"가속! 현재 속도: {self.speed}km/h")
def brake(self):
"""브레이크"""
if self.speed > 0:
self.speed -= 10
print(f"감속! 현재 속도: {self.speed}km/h")
else:
print("이미 정지해 있습니다!")
def change_color(self, new_color):
"""색깔 바꾸기"""
old_color = self.color
self.color = new_color
print(f"색깔 변경: {old_color} → {new_color}")
# 자동차 운전하기
my_car = Car()
my_car.accelerate() # 가속! 현재 속도: 10km/h
my_car.accelerate() # 가속! 현재 속도: 20km/h
my_car.brake() # 감속! 현재 속도: 10km/h
my_car.change_color("빨강") # 색깔 변경: 흰색 → 빨강
📱 실용적인 예시들
예시 1: 핸드폰 클래스
class Phone:
def __init__(self):
# 속성들
self.brand = "삼성"
self.model = "갤럭시"
self.battery = 100
self.is_on = False
def power_on(self):
"""전원 켜기"""
if not self.is_on:
self.is_on = True
print("📱 핸드폰이 켜졌습니다!")
else:
print("이미 켜져 있습니다!")
def power_off(self):
"""전원 끄기"""
if self.is_on:
self.is_on = False
print("📱 핸드폰이 꺼졌습니다!")
else:
print("이미 꺼져 있습니다!")
def make_call(self, number):
"""전화 걸기"""
if self.is_on and self.battery > 0:
self.battery -= 5
print(f"📞 {number}로 전화를 겁니다!")
print(f"배터리: {self.battery}%")
else:
print("전원이 꺼져있거나 배터리가 없습니다!")
def charge(self):
"""충전하기"""
if self.battery < 100:
self.battery = 100
print("🔋 충전 완료! 배터리: 100%")
else:
print("이미 충전이 완료되었습니다!")
# 핸드폰 사용하기
my_phone = Phone()
my_phone.power_on() # 전원 켜기
my_phone.make_call("010-1234-5678") # 전화 걸기
my_phone.make_call("010-9876-5432") # 또 전화 걸기
my_phone.charge() # 충전하기
my_phone.power_off() # 전원 끄기
예시 2: 은행 계좌 클래스
class BankAccount:
def __init__(self):
# 속성들
self.owner = "kim_cheolsu"
self.balance = 0
self.account_number = "123-456-789"
def deposit(self, amount):
"""입금하기"""
if amount > 0:
self.balance += amount
print(f"💰 {amount:,}원 입금완료!")
print(f"잔액: {self.balance:,}원")
else:
print("0원보다 큰 금액을 입금해주세요!")
def withdraw(self, amount):
"""출금하기"""
if amount > 0:
if amount <= self.balance:
self.balance -= amount
print(f"💸 {amount:,}원 출금완료!")
print(f"잔액: {self.balance:,}원")
else:
print("잔액이 부족합니다!")
else:
print("0원보다 큰 금액을 출금해주세요!")
def check_balance(self):
"""잔액 조회"""
print(f"💳 {self.owner}님의 계좌")
print(f"계좌번호: {self.account_number}")
print(f"현재 잔액: {self.balance:,}원")
# 은행 계좌 사용하기
account = BankAccount()
account.check_balance() # 잔액 조회
account.deposit(50000) # 5만원 입금
account.deposit(30000) # 3만원 입금
account.withdraw(20000) # 2만원 출금
account.withdraw(100000) # 10만원 출금 시도 (잔액 부족)
account.check_balance() # 최종 잔액 조회
예시 3: 게임 캐릭터 클래스
class GameCharacter:
def __init__(self):
# 속성들
self.name = "전사"
self.level = 1
self.hp = 100
self.max_hp = 100
self.attack_power = 15
def attack(self, target_name):
"""공격하기"""
print(f"⚔️ {self.name}가 {target_name}을 공격!")
print(f"데미지: {self.attack_power}")
def take_damage(self, damage):
"""데미지 받기"""
self.hp -= damage
if self.hp < 0:
self.hp = 0
print(f"💥 {self.name}가 {damage} 데미지를 받았습니다!")
print(f"HP: {self.hp}/{self.max_hp}")
if self.hp == 0:
print("💀 캐릭터가 쓰러졌습니다!")
def heal(self, amount):
"""회복하기"""
old_hp = self.hp
self.hp += amount
if self.hp > self.max_hp:
self.hp = self.max_hp
healed = self.hp - old_hp
print(f"💚 {healed} HP 회복!")
print(f"HP: {self.hp}/{self.max_hp}")
def level_up(self):
"""레벨업"""
self.level += 1
self.max_hp += 20
self.hp = self.max_hp
self.attack_power += 5
print(f"🎉 레벨업! {self.name} Lv.{self.level}")
print(f"HP: {self.max_hp}, 공격력: {self.attack_power}")
# 게임 플레이
character = GameCharacter()
character.attack("슬라임") # 공격
character.take_damage(30) # 데미지 받기
character.heal(20) # 회복
character.level_up() # 레벨업
character.attack("오크") # 더 강한 공격
🎯 여러 객체로 상호작용하기
예시: 학생들 간의 상호작용
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
self.energy = 100
def greet(self, other_student):
"""다른 학생에게 인사하기"""
print(f"{self.name}: 안녕 {other_student.name}!")
print(f"{other_student.name}: 안녕 {self.name}!")
def study_together(self, other_student):
"""함께 공부하기"""
print(f"📚 {self.name}와 {other_student.name}가 함께 공부합니다!")
self.energy -= 20
other_student.energy -= 20
print(f"{self.name} 에너지: {self.energy}")
print(f"{other_student.name} 에너지: {other_student.energy}")
def rest(self):
"""휴식하기"""
self.energy += 30
if self.energy > 100:
self.energy = 100
print(f"😴 {self.name}가 휴식합니다. 에너지: {self.energy}")
# 학생들 만들기
kim_cheolsu = Student("kim_cheolsu", 2)
lee_younghee = Student("lee_younghee", 2)
park_minsu = Student("park_minsu", 1)
# 학생들 간의 상호작용
kim_cheolsu.greet(lee_younghee) # 인사하기
kim_cheolsu.study_together(lee_younghee) # 함께 공부하기
park_minsu.greet(kim_cheolsu) # park_minsu가 kim_cheolsu에게 인사
kim_cheolsu.rest() # kim_cheolsu 휴식
lee_younghee.rest() # lee_younghee 휴식
📊 속성과 메서드 정리
속성 vs 메서드 구분
class Car:
def __init__(self):
# ✅ 속성 (정보/상태)
self.brand = "현대" # 브랜드
self.color = "빨강" # 색깔
self.speed = 0 # 속도
self.fuel = 50 # 연료량
# ✅ 메서드 (행동/기능)
def start_engine(self): # 시동 걸기
print("부릉부릉! 시동이 걸렸습니다!")
def drive(self, distance): # 운전하기
fuel_needed = distance / 10
if self.fuel >= fuel_needed:
self.fuel -= fuel_needed
print(f"{distance}km 운전했습니다!")
print(f"남은 연료: {self.fuel}L")
else:
print("연료가 부족합니다!")
def refuel(self, amount): # 주유하기
self.fuel += amount
print(f"{amount}L 주유했습니다!")
print(f"현재 연료: {self.fuel}L")
속성 접근 패턴
class Pet:
def __init__(self):
self.name = "뽀삐"
self.age = 3
self.happiness = 80
def show_status(self):
"""상태 보여주기"""
print(f"=== {self.name}의 상태 ===")
print(f"나이: {self.age}세")
print(f"행복도: {self.happiness}/100")
def play(self):
"""놀아주기"""
self.happiness += 20
if self.happiness > 100:
self.happiness = 100
print(f"🎾 {self.name}와 신나게 놀았습니다!")
def feed(self):
"""밥 주기"""
self.happiness += 15
if self.happiness > 100:
self.happiness = 100
print(f"🍖 {self.name}에게 맛있는 밥을 줬습니다!")
# 애완동물 키우기
my_pet = Pet()
my_pet.show_status() # 현재 상태
my_pet.play() # 놀아주기
my_pet.feed() # 밥 주기
my_pet.show_status() # 변화된 상태
🚨 자주 발생하는 오류
오류 1: self 빼먹기
# ❌ 틀린 예 - self 없음
class Student:
def __init__(): # self가 없음!
name = "kim_cheolsu" # self.name이 아님!
def introduce(): # self가 없음!
print(f"안녕하세요!")
# ✅ 올바른 예 - self 포함
class Student:
def __init__(self): # self 필수!
self.name = "kim_cheolsu" # self.name으로 속성 설정
def introduce(self): # self 필수!
print(f"안녕하세요! {self.name}입니다!")
오류 2: 속성 접근 시 self 누락
class Car:
def __init__(self):
self.speed = 0
def accelerate(self):
# ❌ 틀린 예
# speed += 10 # NameError! self.speed여야 함
# ✅ 올바른 예
self.speed += 10
print(f"현재 속도: {self.speed}km/h")
오류 3: 메서드 호출 시 괄호 누락
class Student:
def __init__(self):
self.name = "kim_cheolsu"
def introduce(self):
print(f"안녕하세요! {self.name}입니다!")
student = Student()
# ❌ 틀린 예 - 괄호 없음
# student.introduce # 메서드가 실행되지 않음
# ✅ 올바른 예 - 괄호 포함
student.introduce() # 메서드 실행됨
💡 퀴즈: 속성과 메서드 이해도 체크
Q1. 다음 중 속성(Attribute)에 해당하는 것은?
class Car:
def __init__(self):
self.color = "빨강" # A
def start_engine(self): # B
print("시동!")
def drive(self): # C
print("운전 중!")
- A만
- B와 C만
- A, B, C 모두
- 없음
💡 정답 확인
정답: 1번 (A만)
속성은 객체가 가지는 정보나 데이터입니다. self.color
는 자동차의 색깔 정보를 저장하는 속성이고, start_engine()
과 drive()
는 행동을 나타내는 메서드입니다.
Q2. self의 역할은 무엇인가요?
- 클래스의 이름
- 객체 자신을 가리키는 키워드
- 메서드의 이름
- 속성의 이름
💡 정답 확인
정답: 2번 (객체 자신을 가리키는 키워드)
self
는 현재 객체 자신을 가리키는 특별한 키워드로, 객체의 속성에 접근하거나 메서드를 호출할 때 사용합니다.
Q3. 다음 코드의 실행 결과는?
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
counter = Counter()
counter.increment()
counter.increment()
print(counter.count)
- 0
- 1
- 2
- 오류 발생
💡 정답 확인
정답: 3번 (2)
counter.count
는 0으로 시작하고, increment()
메서드를 두 번 호출하여 각각 1씩 증가시키므로 최종값은 2입니다.
✅ 속성과 메서드 마스터 체크리스트
✅ 속성과 메서드 마스터 체크리스트
🌟 다음 단계 미리보기
속성과 메서드의 기본을 익혔으니, 이제 더욱 유연한 객체를 만들어보겠습니다!
다음 토픽에서는:
- 생성자 매개변수: 객체 생성 시 정보 전달하기
- 다양한 초기화: 같은 클래스로 다른 객체들 만들기
- self의 심화: 객체별 고유한 정보 관리
예를 들어:
class Student:
def __init__(self, name, age, grade): # 매개변수로 정보 받기
self.name = name # 각자 다른 이름
self.age = age # 각자 다른 나이
self.grade = grade # 각자 다른 학년
# 서로 다른 학생들 만들기
kim_cheolsu = Student("kim_cheolsu", 16, 2)
lee_younghee = Student("lee_younghee", 15, 1)
park_minsu = Student("park_minsu", 17, 3)
각 객체가 고유한 정보를 가지게 됩니다! 🚀
Last updated on