728x90
반응형
Overview
Python 클래스에는 세 가지 종류의 메서드가 있다. 이들의 차이를 제대로 이해하면 더 깔끔하고 효율적인 코드를 작성할 수 있다.

1. Instance Method (인스턴스 메서드)
가장 일반적인 메서드로, 객체(인스턴스)가 호출하는 메서드 이다.
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def introduce(self): # 인스턴스 메서드
return f"안녕하세요, 저는 {self.name}이고 {self.grade}학년입니다."
# 사용
student = Student("철수", 3)
print(student.introduce()) # 안녕하세요, 저는 철수이고 3학년입니다.
특징
- 첫 번째 인자로 `self` 를 받음
- 인스턴스의 속성과 메서드에 접근 가능
- 객체를 생성해야만 사용 가능
언제 사용하나요?
- 객체의 데이터(self.name, self.grade 등)를 사용하거나 수정해야 할 때 사용
2. Class Method (클래스 메서드)
클래스 자체와 관련된 메서드로, `@classmethod` 데코레이터를 사용한다.
class Student:
student_count = 0 # 클래스 변수
def __init__(self, name, grade):
self.name = name
self.grade = grade
Student.student_count += 1
@classmethod
def get_student_count(cls): # 클래스 메서드
return f"총 학생 수: {cls.student_count}명"
@classmethod
def from_string(cls, student_str): # 대체 생성자
name, grade = student_str.split('-')
return cls(name, int(grade))
# 사용
student1 = Student("철수", 3)
student2 = Student("영희", 2)
print(Student.get_student_count()) # 총 학생 수: 2명
# 대체 생성자로 객체 생성
student3 = Student.from_string("민수-1")
print(student3.name) # 민수
특징
- 첫 번째 인자로 `cls` (클래스 자체)를 받음
- 클래스 변수에 접근 가능
- 객체 생성 없이도 호출 가능
- 클래스를 통해 호출: `ClassName.method()`
언제 사용하나요?
- 클래스 변수를 다룰 때
- 대체 생성자(팩토리 메서드)를 만들 때
- 클래스 전체와 관련된 기능이 필요할 때
3. Static Method (정적 메서드)
클래스나 인스턴스와 독립적인 메서드로, `@staticmethod` 데코레이터를 사용한다.
class MathUtils:
@staticmethod
def add(x, y):
return x + y
@staticmethod
def is_adult(age):
return age >= 18
@staticmethod
def validate_email(email):
return '@' in email and '.' in email
# 사용
print(MathUtils.add(5, 3)) # 8
print(MathUtils.is_adult(20)) # True
print(MathUtils.validate_email("test@email.com")) # True
# 객체를 만들어서 호출해도 됨 (하지만 굳이 그럴 필요 없음)
util = MathUtils()
print(util.add(10, 20)) # 30
특징
- `self` 나 `cls` 인자를 받지 않음
- 클래스/인스턴스의 상태와 무관
- 일반 함수처럼 동작하지만 클래스 안에 정의
- 클래스를 통해 호출: `ClassName.method()`
언제 사용하나요?
- 클래스나 인스턴스의 데이터가 필요 없을 때
- 유틸리티 함수를 클래스로 그룹화할 때
- 논리적으로 클래스에 속하지만 독립적인 기능일 때
비교 정리
| 구분 | Instance Method | Class Method | Static Method |
| 데코레이터 | 없음 | `@classmethod` | `@staticmethod` |
| 첫 번째 인자 | `self` | `cls` | 없음 |
| 인스턴스 변수 접근 | 가능 | 불가능 | 불가능 |
| 클래스 변수 접근 | 가능 | 가능 | 불가능 |
| 호출 방법 | `객체.method()` | `클래스.method()` | `클래스.method()` |
실전 예제: 날짜 클래스
세 가지 메서드를 모두 활용한 예제이다.
from datetime import datetime
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
# Instance Method: 객체의 데이터 사용
def format(self):
return f"{self.year}년 {self.month}월 {self.day}일"
# Class Method: 대체 생성자
@classmethod
def today(cls):
now = datetime.now()
return cls(now.year, now.month, now.day)
@classmethod
def from_string(cls, date_string):
year, month, day = map(int, date_string.split('-'))
return cls(year, month, day)
# Static Method: 독립적인 유틸리티
@staticmethod
def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
@staticmethod
def validate_date(year, month, day):
if month < 1 or month > 12:
return False
if day < 1 or day > 31:
return False
return True
# 사용 예시
date1 = Date(2025, 10, 21)
print(date1.format()) # Instance Method: 2025년 10월 21일
date2 = Date.today() # Class Method: 오늘 날짜로 생성
date3 = Date.from_string("2025-12-25") # Class Method: 문자열로 생성
print(Date.is_leap_year(2024)) # Static Method: True
print(Date.validate_date(2025, 2, 30)) # Static Method: False
결론
- Instance Method: 객체의 데이터를 사용/수정할 때
- Class Method: 클래스 변수를 다루거나 대체 생성자가 필요할 때
- Static Method: 클래스와 논리적으로 관련있지만 독립적인 기능일 때
각 메서드의 특징을 이해하고 적재적소에 사용하면, 더 읽기 쉽고 유지보수하기 좋은 코드를 작성할 수 있다!
Reference
- Real Python - https://realpython.com/instance-class-and-static-methods-demystified/
- GeeksforGeeks - https://www.geeksforgeeks.org/python/class-method-vs-static-method-vs-instance-method-in-python/
- PYnative - https://pynative.com/python-class-method-vs-static-method-vs-instance-method/
- Stack Overflow - https://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python
- DigitalOcean - https://www.digitalocean.com/community/tutorials/python-static-method
- StackAbuse - https://stackabuse.com/pythons-classmethod-and-staticmethod-explained/
728x90
반응형
'Launguage' 카테고리의 다른 글
| Python 예외 처리와 컨텍스트 매니저 완벽 가이드 (0) | 2025.12.19 |
|---|---|
| Python 상속과 다형성 완벽 가이드 (0) | 2025.12.05 |
| Python 클래스 데코레이터 완벽 가이드 (0) | 2025.11.21 |
| Python 매직 메서드 완벽 가이드 (0) | 2025.11.07 |
| Python 가상환경 설정(WSL2 Ubuntu) (0) | 2023.10.10 |