한양과학기술고등학교

에듀테크 프로젝트 대시보드

메서드 종류 · property

classmethod staticmethod property getter/setter

인스턴스 메서드 외에 @classmethod·@staticmethod·@property 세 가지가 있습니다.

1. 세 가지 비교

종류첫 인자용도
인스턴스 메서드self인스턴스 상태 사용/변경
@classmethodcls대체 생성자, 클래스 상태
@staticmethod없음논리적으로 관련된 순수 함수

2. classmethod — 대체 생성자

class Date:
    def __init__(self, year, month, day):
        self.year, self.month, self.day = year, month, day

    @classmethod
    def from_string(cls, s):         # cls == Date (상속 시 하위 클래스)
        y, m, d = map(int, s.split("-"))
        return cls(y, m, d)

    @classmethod
    def today(cls):
        import datetime
        n = datetime.date.today()
        return cls(n.year, n.month, n.day)

Date.from_string("2024-01-15")

3. staticmethod

class Temperature:
    @staticmethod
    def c_to_f(celsius):             # self/cls 불필요
        return celsius * 9 / 5 + 32

Temperature.c_to_f(100)             # => 212.0
# 그냥 모듈 함수로 둬도 되지만, 개념적으로 묶고 싶을 때

4. property — 계산된 속성

class Circle:
    def __init__(self, radius):
        self.radius = radius

    @property
    def area(self):                  # 괄호 없이 c.area 로 접근
        return 3.14159 * self.radius ** 2

    @property
    def diameter(self):
        return self.radius * 2

c = Circle(5)
c.area           # => 78.53...  (메서드 아니라 속성처럼)
# c.area = 10    # AttributeError (setter 없음 → 읽기 전용)

5. setter 로 검증

class Account:
    def __init__(self, balance):
        self._balance = balance

    @property
    def balance(self):
        return self._balance

    @balance.setter
    def balance(self, value):
        if value < 0:
            raise ValueError("잔액은 음수 불가")
        self._balance = value

a = Account(100)
a.balance = 50        # setter 호출
# a.balance = -1      # ValueError
property 를 언제?
  • 처음엔 그냥 공개 속성으로 시작 — 나중에 검증·계산이 필요해지면 property 로 교체(호출부 안 바뀜)
  • getter/setter 를 처음부터 만드는 건 자바식 습관, 파이썬답지 않음

6. __slots__ (메모리 최적화)

class Point:
    __slots__ = ("x", "y")           # __dict__ 대신 고정 슬롯
    def __init__(self, x, y):
        self.x, self.y = x, y

# 인스턴스 수천만 개일 때 메모리 크게 절감
# 단점: 동적 속성 추가 불가, 다중 상속 제약
"특별한 경우라도 규칙을 어길 만큼 특별하지는 않다"