[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,87 +2,244 @@
|
||||
id: wiki-2026-0508-inheritance-and-polymorphism
|
||||
title: Inheritance and Polymorphism
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [CS-OOP-001]
|
||||
aliases: [OOP Inheritance, Subtype Polymorphism, Method Dispatch]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [programming, oop, inheritance, polymorphism, software-design]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [oop, programming-language, type-theory, polymorphism]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: multi
|
||||
framework: oop
|
||||
---
|
||||
|
||||
# Inheritance and Polymorphism (상속과 다형성)
|
||||
# Inheritance and Polymorphism
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "부모의 자산을 물려받아 지식을 확장하고, 하나의 이름으로 수만 가지의 다채로운 행동을 수행하라" — 코드의 재사용성을 극대화하는 상속(Inheritance)과, 동일한 메시지에 대해 객체마다 다르게 반응하도록 설계하는 다형성(Polymorphism)을 통해 유연하고 확장 가능한 시스템을 구축하는 객체 지향의 핵심 원리.
|
||||
## 매 한 줄
|
||||
> **"매 inheritance 의 mechanism — polymorphism 의 outcome"**. 매 inheritance 의 code reuse + 매 is-a 의 subtype relationship; 매 polymorphism 의 same interface 의 different behavior. 매 modern 2026 의 view 의 "favor composition over inheritance" 의 default — Go/Rust 의 inheritance-free, but interface-polymorphism 의 universal. 매 LLM-generated code 의 over-inheritance 의 common antipattern.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Abstraction and Specialization" — 공통된 특성을 추상 클래스나 인터페이스로 정의하고, 이를 상속받아 구체적인 기능을 구현함으로써 복잡한 시스템의 계층 구조를 체계화하는 설계 패턴.
|
||||
- **핵심 개념:**
|
||||
- **Inheritance:** 기존 클래스(Parent)의 필드와 메서드를 새로운 클래스(Child)가 물려받아 확장. "Is-a" 관계 형성.
|
||||
- **Polymorphism:** 하나의 변수나 메서드가 여러 타입을 가질 수 있는 성질. 오버라이딩(Overriding)과 오버로딩(Overloading)을 통해 실현.
|
||||
- **의의:** 결합도(Coupling)를 낮추고 응집도(Cohesion)를 높여, 코드 한 곳을 수정했을 때 시스템 전체에 미치는 악영향을 최소화함.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 깊은 상속 계층이 오히려 유지보수를 어렵게 만든다는 반성 하에, 최근에는 "상속보다 합성(Composition over Inheritance)"을 우선시하는 설계 철학이 대두됨.
|
||||
- **정책 변화:** Antigravity 프로젝트의 에이전트 스킬 설계 시, 기본 기능을 상속받되 구체적인 동작은 다형성을 활용하여 각 에이전트의 특성에 맞춰 구현하는 '플러그인 아키텍처'를 준수함.
|
||||
### 매 inheritance 의 종류
|
||||
- **Single inheritance**: 매 one parent class (Java, Kotlin, C#).
|
||||
- **Multiple inheritance**: 매 N parents — diamond problem (C++, Python via MRO).
|
||||
- **Mixins / traits**: 매 horizontal composition (Rust traits, Scala traits, Python mixins).
|
||||
- **Prototype-based**: 매 object → object delegation (JavaScript, Lua).
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Software-Architecture-Patterns, [[Functional-Programming|Functional-Programming]], [[Domain-Driven-Design-DDD|Domain-Driven-Design-DDD]],[[_system|system]]-Design-for-AI-Scale
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Inheritance-and-Polymorphism.md
|
||||
### 매 polymorphism 의 종류
|
||||
- **Subtype polymorphism**: 매 subclass 의 parent 의 substitute (Liskov LSP).
|
||||
- **Parametric polymorphism (generics)**: 매 type parameter — `List<T>`.
|
||||
- **Ad-hoc polymorphism (overloading)**: 매 same name 의 different signatures.
|
||||
- **Row polymorphism**: 매 structural — TypeScript / OCaml 의 records.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. **Domain hierarchy**: 매 `Animal → Dog/Cat`. Often overused.
|
||||
2. **Plugin architecture**: 매 `Plugin` interface + N implementations.
|
||||
3. **AST transformation**: 매 `Visitor` pattern + node hierarchy.
|
||||
4. **Strategy pattern**: 매 interchangeable algorithms via interface.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### 매 subtype polymorphism (Python ABC + Liskov)
|
||||
```python
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
class Shape(ABC):
|
||||
@abstractmethod
|
||||
def area(self) -> float: ...
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
class Circle(Shape):
|
||||
def __init__(self, r: float): self.r = r
|
||||
def area(self) -> float: return 3.14159 * self.r ** 2
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
class Rectangle(Shape):
|
||||
def __init__(self, w: float, h: float): self.w, self.h = w, h
|
||||
def area(self) -> float: return self.w * self.h
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
# Polymorphic use — caller knows nothing about concrete type
|
||||
def total_area(shapes: list[Shape]) -> float:
|
||||
return sum(s.area() for s in shapes)
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
print(total_area([Circle(2), Rectangle(3, 4)])) # 24.566...
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 매 composition over inheritance (modern preferred)
|
||||
```python
|
||||
# ❌ Inheritance-heavy — fragile
|
||||
class Animal:
|
||||
def move(self): print("move")
|
||||
class Bird(Animal):
|
||||
def fly(self): print("fly")
|
||||
class Penguin(Bird): # Penguin 의 fly X — Liskov violation
|
||||
def fly(self): raise NotImplementedError
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
# ✅ Composition-based — flexible
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
class Mover(Protocol):
|
||||
def move(self) -> str: ...
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
@dataclass
|
||||
class Walker:
|
||||
def move(self) -> str: return "walk"
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
@dataclass
|
||||
class Flyer:
|
||||
def move(self) -> str: return "fly"
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
@dataclass
|
||||
class Animal2:
|
||||
name: str
|
||||
mover: Mover # plug in capability — no inheritance
|
||||
|
||||
penguin = Animal2("Penguin", Walker())
|
||||
sparrow = Animal2("Sparrow", Flyer())
|
||||
print(penguin.mover.move(), sparrow.mover.move())
|
||||
```
|
||||
|
||||
### 매 generic parametric polymorphism (TypeScript)
|
||||
```typescript
|
||||
// Same code for any T
|
||||
function head<T>(xs: T[]): T | undefined {
|
||||
return xs[0];
|
||||
}
|
||||
|
||||
const n: number | undefined = head([1, 2, 3]);
|
||||
const s: string | undefined = head(["a", "b"]);
|
||||
|
||||
// Bounded generic — T must be Comparable
|
||||
interface Comparable<T> { compareTo(other: T): number; }
|
||||
|
||||
function max<T extends Comparable<T>>(xs: T[]): T {
|
||||
return xs.reduce((acc, x) => x.compareTo(acc) > 0 ? x : acc);
|
||||
}
|
||||
```
|
||||
|
||||
### 매 trait-based polymorphism (Rust — no inheritance)
|
||||
```rust
|
||||
trait Area {
|
||||
fn area(&self) -> f64;
|
||||
}
|
||||
|
||||
struct Circle { r: f64 }
|
||||
struct Square { side: f64 }
|
||||
|
||||
impl Area for Circle {
|
||||
fn area(&self) -> f64 { 3.14159 * self.r * self.r }
|
||||
}
|
||||
impl Area for Square {
|
||||
fn area(&self) -> f64 { self.side * self.side }
|
||||
}
|
||||
|
||||
// Static dispatch (zero-cost generics)
|
||||
fn print_area_static<T: Area>(s: &T) {
|
||||
println!("{}", s.area());
|
||||
}
|
||||
|
||||
// Dynamic dispatch (vtable)
|
||||
fn print_area_dyn(s: &dyn Area) {
|
||||
println!("{}", s.area());
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let shapes: Vec<Box<dyn Area>> = vec![
|
||||
Box::new(Circle { r: 2.0 }),
|
||||
Box::new(Square { side: 3.0 }),
|
||||
];
|
||||
for s in &shapes { print_area_dyn(s.as_ref()); }
|
||||
}
|
||||
```
|
||||
|
||||
### 매 visitor pattern (AST traversal)
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
# AST hierarchy
|
||||
@dataclass
|
||||
class Num: value: float
|
||||
@dataclass
|
||||
class Add: left: "Expr"; right: "Expr"
|
||||
@dataclass
|
||||
class Mul: left: "Expr"; right: "Expr"
|
||||
|
||||
Expr = Union[Num, Add, Mul]
|
||||
|
||||
# Polymorphic dispatch via match (Python 3.10+)
|
||||
def evaluate(e: Expr) -> float:
|
||||
match e:
|
||||
case Num(v): return v
|
||||
case Add(l, r): return evaluate(l) + evaluate(r)
|
||||
case Mul(l, r): return evaluate(l) * evaluate(r)
|
||||
|
||||
# (3 + 4) * 5
|
||||
print(evaluate(Mul(Add(Num(3), Num(4)), Num(5)))) # 35
|
||||
```
|
||||
|
||||
### 매 LSP-violation 의 detector (mypy + tests)
|
||||
```python
|
||||
# Runtime LSP check — for each subclass override, parameter contravariant + return covariant
|
||||
import inspect
|
||||
from typing import get_type_hints
|
||||
|
||||
def check_lsp(parent: type, child: type) -> list[str]:
|
||||
issues = []
|
||||
for name in dir(parent):
|
||||
if name.startswith("_") or not callable(getattr(parent, name)):
|
||||
continue
|
||||
try:
|
||||
p_hints = get_type_hints(getattr(parent, name))
|
||||
c_hints = get_type_hints(getattr(child, name))
|
||||
except Exception:
|
||||
continue
|
||||
# Return type must be subtype of parent's return
|
||||
if "return" in p_hints and "return" in c_hints:
|
||||
if not issubclass(c_hints["return"], p_hints["return"]):
|
||||
issues.append(f"{child.__name__}.{name}: return type widens parent")
|
||||
return issues
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 is-a 의 stable | Inheritance OK — keep depth ≤ 2 |
|
||||
| 매 has-a / can-do | Composition + protocol/interface |
|
||||
| 매 cross-cutting (logging, metrics) | Decorator / mixin / aspect |
|
||||
| 매 algorithm variants | Strategy pattern (composition) |
|
||||
| 매 type-safe collections | Parametric generics (`List<T>`) |
|
||||
| 매 closed AST / variant data | Sum types + pattern match (Rust enum, Scala sealed) |
|
||||
|
||||
**기본값**: 매 composition + interface — inheritance 의 only when 명확 is-a + LSP-honoring.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Object-Oriented Programming (OOP)]] · [[Type Theory]]
|
||||
- 변형: [[Subtype Polymorphism]] · [[Parametric Polymorphism]] · [[Ad-hoc Polymorphism]]
|
||||
- 응용: [[Strategy Pattern]] · [[Visitor Pattern]] · [[Plugin Architecture]]
|
||||
- Adjacent: [[Liskov Substitution Principle]] · [[Composition over Inheritance]] · [[Duck Typing]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 boilerplate 의 generation (interface + N impls) / 매 LSP audit / 매 inheritance-to-composition refactor.
|
||||
**언제 X**: 매 deep inheritance design — 매 LLM 의 over-inherit 의 tendency. Manual review 필수.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **매 deep inheritance**: 매 4+ levels — fragile base class problem.
|
||||
- **매 LSP violation**: 매 subclass 의 throws on parent-supported method (Penguin.fly).
|
||||
- **매 inheritance for code reuse only**: 매 not is-a — use composition.
|
||||
- **매 god parent class**: 매 parent 의 every responsibility — SRP violation.
|
||||
- **매 multiple inheritance 의 diamond ignore**: 매 MRO 의 surprise behavior.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Gamma et al. *Design Patterns* 1994; Liskov & Wing *A Behavioral Notion of Subtyping* 1994; Effective Java Item 18 "Favor composition" 2018).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — types of inheritance + polymorphism + multi-language patterns |
|
||||
|
||||
Reference in New Issue
Block a user