Python: classes and inheritance

xsldihsl·2024년 2월 27일

Python

목록 보기
3/5

처음 python 에 관한 글을 올렸을 때 class 와 instance 에 관해 간단히 얘기하고 넘어갔는데, 오늘은 조금 더 자세히 다루어보려 한다.

Contents

  1. Class & Instances
    1-1. Attributes & methods
  2. Inheritance

1. Class & Instances

  • Class: A blueprint/prototype used to create instance objects.
  • Instance: A specific realization of any object.

Class 와 instance 를 설명할 때 주로 "자동차" 를 예로 드는데, 이 비유는 매우 직관적이라 이해가 용이하다.

(1) 자동차를 만들기 위해서 쓰이는 설계도나 계획서 같은 것이 class 라고 할 수 있으며, 그 blueprint 에는 속성 (attributes)행위 (methods) 가 정의된다.

  • 자동차의 속성
    ex) 색상, 모델
  • 자동차의 행위
    ex) 가속, 정지

(2) 그렇다면 그 class 계획서의 정의에 기반해 실제로 생성된 object, 즉, 자동차instance 가 된다.


1-(1). Attributes & Methods

앞서 언급한 attributes 와 methods 에 관해 간단히 알아보자.

Attributes: Class 내에서 지정된 variables
Methods: Class 내에서 정의된 functions


2. Inheritance

Python 의 class 상속이란, child/sub class 생성 시 parent/super class 에 선언된 attributes/variables, methods 등을 가져와 사용할 수 있는 것이다.

Inheritance 는 동일한 코드를 여러 class 에서 조금씩 수정해 사용하거나, module 에 내장된 class 변경 시 주로 사용된다. 그렇게 함으로써 전체 코드를 바꾸거나 module 내의 코드를 바꾸지 않고도 원하는 코드로 수정이 가능하다.

다음의 Monster 예시를 보자.

# Parent class
class Monster():
	def __init__(self, hp):
    	self.hp = hp
       
   	def attack(self, damage):
    	self.hp -= damage
       
   	def status_check(self):
    	print(f"monster's hp: {self.hp}
       

# Child class
class FireMonster(Monster):
 	def __init__(self, hp):
    	self.attribute = "fire"
        super().__init__(hp) # same as parent class's __init__: self.hp = hp
      
    def status_check(self):
    	print(f"Fire monster's hp: {self.hp}")
       

# Child class
class IceMonster(Monster):
	def __init__(self, hp):
    	self.attribute = "water"
       
    def status_check(self):
    	print(f"Ice monster's hp: {self.hp}")


# Instances
fire_monster = FireMonster(hp = 100)
fire_monster.attack(20)
fire_monster.status_check()

ice_monster = IceMonster(hp = 100)
ice_monster.attack(50)
ice_monster.status_check()

class Monster() 는 Monster 가 가져야 할 속성들과 행위들을 정의하는 parent class 이고, class FireMonster() 와 IceMonster() 를 child classes 로 갖는다. 따라서 상속이 발생하게 되는데, FireMonster 와 IceMonster 둘 다 attack() 을 method 로 갖고 있지 않지만 적용할 수 있는 것이 그 쓰임이다.

0개의 댓글