본문 바로가기
C.W.K.
Stream
Lesson 01 of 07 · published

클래스와 인스턴스 — 상태와 행동을 한 객체에 묶기

~22 min · class, init, self, instance

Level 0호기심
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete

class는 객체를 만드는 새 타입을 정의해

클래스를 호출하면 먼저 __new__가 인스턴스를 만들고 __init__이 그 인스턴스의 초기 상태를 세워. 보통은 __init__만 직접 작성하면 돼.

self는 현재 수신자야

메서드를 obj.method(x)로 호출하면 Python이 obj를 첫 인자 self로 묶어. 클래스에서 함수를 직접 꺼내 호출하면 그 인스턴스를 명시해야 하므로 “bound method”의 정체가 보여.

각 인스턴스는 자기 상태를 가진다

같은 클래스에서 만든 객체도 __init__에서 self에 저장한 값은 서로 달라. 객체는 그 상태를 지키는 메서드와 불변조건을 한 경계에 모을 때 값어치를 해.

Code

가장 작은 클래스·python
class Circle:
    def __init__(self, radius):
        self.radius = radius            # 인스턴스에 속성

    def area(self):
        return 3.14159 * self.radius ** 2

c = Circle(5)
print(c.radius)         # 5
print(c.area())         # 78.54

# self 는 인스턴스 — Python 이 자동 채움
print(Circle.area(c))   # 78.54  (클래스에서 호출, 인스턴스 명시)
__new__와 __init__의 역할·python
class Logger:
    def __new__(cls, *args, **kwargs):
        print("__new__: 인스턴스 생성")
        instance = super().__new__(cls)     # 실제 생성
        return instance

    def __init__(self, name):
        print("__init__: setup")
        self.name = name

l = Logger("main")
# __new__: 인스턴스 생성
# __init__: setup

# 99% 는 __init__ 만 override
인스턴스마다 따로 남는 상태·python
class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        return self.balance

a = Account("alice")
b = Account("bob", 100)

a.deposit(50)
b.deposit(25)

print(a.owner, a.balance)        # alice 50
print(b.owner, b.balance)        # bob 125    — 독립 state
묶인 메서드의 실제 호출 모양·python
class Greeter:
    def __init__(self, name):
        self.name = name

    def hi(self):
        return f"hello {self.name}"

g = Greeter("pippa")

# obj.method 가 BOUND 메서드 — 인스턴스 기억
bound = g.hi
print(bound)                # <bound method Greeter.hi of <__main__.Greeter object at ...>>
print(bound())              # 'hello pippa'

# 그냥 Greeter.hi 는 클래스의 함수일 뿐
print(Greeter.hi(g))        # 'hello pippa' — 인스턴스 명시적으로

External links

Exercise

owner와 opening_balance를 받는 BankAccount를 만들고 deposit, withdraw, transfer_to를 구현해. 음수 잔액이 되려 하면 ValueError를 내고, 두 계좌 사이 송금과 잔액 부족 송금을 시험해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.