한 줄 뜻 이미 있는 클래스(부모)의 속성과 메서드를 새 클래스(자식)가 받아 사용하고, 다른 부분만 덧붙이거나 바꾸는 방법이에요. class Truck(Vehicle): 처럼 괄호 안에 부모를 적어요.
왜 필요한가 자전거·트럭·버스가 모두 이름, 바퀴 수, 달린 거리와 drive() 를 가진다면 같은 코드를 세 클래스에 복사해야 해요. 거리 계산을 고칠 때 한 곳을 빠뜨리면 탈것마다 결과가 달라져요.
공통 부분을 Vehicle 에 한 번만 두고 자식은 다른 점만 적으면 고칠 곳이 하나로 줄어요.
일상 비유 가게 프랜차이즈를 떠올려 보세요. 본사 메뉴얼(부모)에 계산·청소·인사 규칙이 있고, 지점(자식)은 그 규칙을 따르면서 지역 메뉴 한두 개만 더해요. 본사가 규칙을 바꾸면 모든 지점에 한 번에 적용돼요.
예제 코드 main.py · 40줄 실행 복사 고쳐 보기 처음 코드로 class Vehicle : def __init__ (self , name, wheels): self .name = name self .wheels = wheels self .km = 0 def drive (self , km): self .km += km return f"{self.name} drove {km}km (total {self.km}km)" def describe (self ): return f"{self.name} on {self.wheels} wheels" class Bicycle (Vehicle ): def __init__ (self , name): super ().__init__ (name, 2 ) def ring (self ): return f"{self.name}: ring ring" class Truck (Vehicle ): def __init__ (self , name, load_limit): super ().__init__ (name, 6 ) self .load_limit = load_limit def describe (self ): base = super ().describe () return f"{base}, carries up to {self.load_limit}kg" bike = Bicycle ("Pedal" ) truck = Truck ("Hauler" , 1000 ) print (bike.drive (5 ))print (truck.drive (40 ))print (bike.describe ())print (truck.describe ())print (bike.ring ())print (isinstance (truck, Vehicle ), Truck .__mro__[1 ].__name__)
고친 코드는 실행 단추로 돌려 볼 수 있어요. 한 줄씩 따라가기와 위 실행 결과는 원래 코드 기준이에요.
한 줄씩 따라가기 시작 전 다음을 누르면 맨 아래 실행 코드의 첫 줄부터 한 줄씩 움직여요. 밝은 띠가 방금 실행한 줄이에요.
처음 이전 다음
실행 결과 Pedal drove 5km (total 5km) Hauler drove 40km (total 40km) Pedal on 2 wheels Hauler on 6 wheels, carries up to 1000kg Pedal: ring ring True Vehicle 서버의 Python 3.12 와 브라우저 안 Python(Pyodide) 두 곳에서 돌려 같게 나온 결과예요.
클래스 그림 Vehicle + name: str + wheels: int + km: int + __init__(name, wheels) + drive(km): str + describe(): str Bicycle + __init__(name) + ring(): str Truck + load_limit: int + __init__(name, load_limit) + describe(): str + 이름 그대로(공개) · # _이름(안쪽용 약속) · - __이름(이름 바뀜) · 밑줄 클래스 변수·@staticmethod·@classmethod · 기울임 @abstractmethod
언제 사용하나 "트럭은 탈것이다"처럼 "~은 ~이다"가 자연스러울 때 여러 클래스가 같은 속성·메서드를 많이 나눠 가질 때 부모가 정한 메서드를 자식마다 조금씩 다르게 하고 싶을 때(덮어쓰기) "~을 가진다"가 더 맞으면(로봇이 배터리를 가진다) 상속 대신 합성을 사용해요. 다음 다음 주제에서 다뤄요.
파이썬은 부모를 여럿 둘 수도 있어요(다중 상속). 찾는 차례는 클래스.__mro__ 로 확인해요.
자주 하는 실수 자식 __init__ 에서 super().__init__() 을 빼먹음 자식이 __init__ 을 새로 쓰면 부모의 __init__ 은 저절로 돌지 않아요. 부모가 채우던 name, km 이 비어서 오류가 나요.
틀린 코드
class Vehicle : def __init__ (self , name): self .name = name self .km = 0 class Bicycle (Vehicle ): def __init__ (self , name): self .basket = True b = Bicycle ("Pedal" ) print (b.name)실행하면 AttributeError: 'Bicycle' object has no attribute 'name'
고친 코드
class Vehicle : def __init__ (self , name): self .name = name self .km = 0 class Bicycle (Vehicle ): def __init__ (self , name): super ().__init__ (name) self .basket = True b = Bicycle ("Pedal" ) print (b.name)실행하면 Pedal
덮어쓴 메서드의 매개변수를 늘림 부모처럼 부르는 코드(v.drive(10))가 자식에서 깨져요. 매개변수를 더할 때는 기본값을 줘서 부모와 같은 꼴로도 부를 수 있게 해요.
틀린 코드
class Vehicle : def drive (self , km): return km class Truck (Vehicle ): def drive (self , km, load): return km * 2 if load else km for v in [Vehicle (), Truck ()]: print (v.drive (10 )) 실행하면 TypeError: Truck.drive() missing 1 required positional argument: 'load'
고친 코드
class Vehicle : def drive (self , km): return km class Truck (Vehicle ): def drive (self , km, load=0 ): return km * 2 if load else km for v in [Vehicle (), Truck ()]: print (v.drive (10 )) 실행하면 10
10
부모 메서드를 클래스 이름으로 부르며 self 를 안 넘김 Vehicle.describe() 처럼 클래스 이름으로 부르면 어느 객체인지 알 수 없어요. super().describe() 는 지금 객체를 알아서 넘겨요.
틀린 코드
class Vehicle : def describe (self ): return "a vehicle" class Truck (Vehicle ): def describe (self ): return Vehicle .describe () + " that carries cargo" print (Truck ().describe ())실행하면 TypeError: Vehicle.describe() missing 1 required positional argument: 'self'
고친 코드
class Vehicle : def describe (self ): return "a vehicle" class Truck (Vehicle ): def describe (self ): return super ().describe () + " that carries cargo" print (Truck ().describe ())실행하면 a vehicle that carries cargo
확인 문제 문제 1
Truck("Mule", 500).describe() 는 무엇을 돌려줄까요?
t = Truck ("Mule" , 500 ) print (t.describe ())1 Mule on 6 wheels 2 Mule on 6 wheels, carries up to 500kg 3 AttributeError 가 나요
답과 까닭 보기 답: 2. Mule on 6 wheels, carries up to 500kg 트럭이 덮어쓴 describe 가 돌아요. 그 안에서 super().describe() 로 부모 문장을 받고 짐 한도를 덧붙여요.
문제 2
bike.describe() 를 부르면 파이썬은 어느 클래스부터 describe 를 찾을까요?
print ([c.__name__ for c in Bicycle .__mro__])1 Vehicle 2 Bicycle 3 object
답과 까닭 보기 답: 2. Bicycle 찾는 차례는 Bicycle → Vehicle → object 예요. Bicycle 에 없으니 다음인 Vehicle 의 것을 사용해요.
이어서 볼 주제 앞 주제 캡슐화 다음 주제 다형성 같이 보면 좋은 주제 합성과 클래스 변수 자주 묻는 것 super() 는 왜 사용하나요? 부모 클래스의 메서드를 지금 객체로 불러요. 자식 __init__ 에서 super().__init__(...) 으로 부모가 채우는 값을 먼저 채우는 게 가장 흔한 쓰임이에요.
부모를 여러 개 둘 수 있나요? 예. class C(A, B): 처럼 사용해요. 메서드를 찾는 차례는 C.__mro__ 로 확인하고, super() 도 그 차례를 따라요.
상속과 합성은 어떻게 고르나요? "트럭은 탈것이다"처럼 ~이다가 맞으면 상속, "로봇은 배터리를 가진다"처럼 ~을 가진다가 맞으면 합성이에요.