PHpullh
학습 라이브러리/Python/클래스 & __init__ & 프로퍼티

PYTHON · 객체지향

클래스 & __init__ & 프로퍼티

Python OOP의 핵심. __init__, @property, @classmethod, @staticmethod.

객체지향입문class__init__@property@classmethod@staticmethod

핵심 설명

Python OOP의 핵심. __init__, @property, @classmethod, @staticmethod.

Python code

from datetime import date

class Person:
    # 클래스 변수 (모든 인스턴스 공유)
    species = "Homo sapiens"

    def __init__(self, name: str, birth_year: int):
        # 인스턴스 변수
        self.name = name
        self._birth_year = birth_year   # 관례적 protected
        self.__secret = "비밀"           # name mangling (private)

    # @property — getter
    @property
    def age(self) -> int:
        return date.today().year - self._birth_year

    # @property.setter
    @age.setter
    def age(self, value: int):
        if value < 0:
            raise ValueError("나이는 0 이상")
        self._birth_year = date.today().year - value

    # @classmethod — cls 인자, 클래스 메서드
    @classmethod
    def from_string(cls, data: str) -> "Person":
        name, year = data.split(",")
        return cls(name.strip(), int(year.strip()))

    # @staticmethod — self/cls 없음, 유틸리티
    @staticmethod
    def is_adult(age: int) -> bool:
        return age >= 18

    def __repr__(self) -> str:
        return f"Person(name={self.name!r}, age={self.age})"

p1 = Person("Alice", 1993)
p2 = Person.from_string("Bob, 1990")
print(p1.age)               # 계산된 나이
print(Person.is_adult(20))  # True
print(repr(p1))

학습 팁

@property로 getter를 만들면 외부에서 obj.age처럼 속성처럼 접근하면서 내부적으로 계산할 수 있습니다.

주의할 점

self.__attr(더블 언더스코어)는 외부에서 직접 접근을 막는 게 아니라 이름 맹글링(_ClassName__attr)으로 변환됩니다. 완전한 private가 아닙니다.

자주 묻는 질문

클래스 & __init__ & 프로퍼티란 무엇인가요?

Python OOP의 핵심. __init__ , @property , @classmethod , @staticmethod .

클래스 & __init__ & 프로퍼티 학습 시 주의할 점은 무엇인가요?

self.__attr (더블 언더스코어)는 외부에서 직접 접근을 막는 게 아니라 이름 맹글링( _ClassName__attr )으로 변환됩니다. 완전한 private가 아닙니다.