topic난이도 · 약 20

클래스 & 상속

`class Parent`, `class Child(Parent)`, `__init__`, `self`, `super()`.

#Python#클래스#상속
왜 배우는가

Java만큼 자주 나오진 않지만 출제되면 클래스 속성 vs 인스턴스 속성의 차이를 묻는다. 이 구분을 모르면 답이 반대로 나온다.

Python 클래스는 Java와 비슷하지만 self(Java의 this)를 명시적으로 써야 한다는 점과, 클래스 변수와 인스턴스 변수의 차이가 더 드러난다는 점이 특징이다.

`super().__init__(name)`으로 부모의 생성자를 호출해야 name이 초기화된다. Python은 다중 상속도 지원하며, MRO(Method Resolution Order)로 메서드 탐색 순서가 결정된다.

핵심 함정 — `클래스.속성`과 `인스턴스.속성`을 같은 이름으로 쓰면, 인스턴스 속성이 클래스 속성을 가린다. `a.x = 5`로 할당하면 그 순간부터 a.x는 인스턴스 속성을 가리킨다.

특수 메서드(Dunder) — `__init__`(생성자), `__str__`(문자열 변환), `__len__`(len()), `__eq__`(==), `__add__`(+). 이름 앞뒤로 두 개의 밑줄이 붙어 'dunder'라 부른다.

실기 드릴 4문항
code실기 드릴 · 코드 추적

다음 Python 코드의 출력은?

python
class A:
    x = 10
    def show(self):
        return self.x * 2

a = A()
a.x = 5
print(a.show())
code실기 드릴 · 코드 추적

다음 Python 코드의 출력은?

python
class Parent:
    def __init__(self):
        self.value = 10
    def show(self):
        return f"Parent: {self.value}"

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.value = 20
    def show(self):
        return f"Child: {self.value}"

c = Child()
print(c.show())
code실기 드릴 · 코드 추적

다음 Python 코드의 출력은?

python
class Counter:
    count = 0

    def __init__(self):
        Counter.count += 1

a = Counter()
b = Counter()
c = Counter()
print(Counter.count)
print(a.count, b.count, c.count)
code실기 드릴 · 코드 추적

다음 Python 코드의 출력은?

python
class Box:
    def __init__(self, v):
        self.v = v
    def __add__(self, other):
        return Box(self.v + other.v)
    def __str__(self):
        return f"Box({self.v})"

a = Box(3)
b = Box(5)
print(a + b)