코딩에서 사용되는 클래스라는 단어의 의미는 '부류'에 가깝다. 부류라는 것은 동일한 범주에 속하는 대상들을 일정한 기준에 따라 나누너 놓은 갈래, 즉 공통점이 가진 것끼리기 나누어 놓다라는 뜻을 말한다.
예를 들어 여기서 comedian는 class
가 된다. 하지만 이 comedian이라는 것은 개념일 뿐 실체가 아니다 . 실체(instance)
는 이영자, 송영이, 양세형, 유병재를 말한다. 그리고 이 실체(instance)
들을 객체(object)
라고 한다.
class Car:
pass
#실체화
hyundai = Car()
bmw = Car()
메소드
라고 부른다. class Car:
def __init__(self, maker, model, horse_power): # 4개
self.maker = maker
self.model = model
self.horse_power = horse_power
hyundai = Car("현대", "제네시스", 500) # init메소드 호출 - 3개
위의 코드에서 의아한 점은 init 메소드에 파라미터는 총 4개인데 클래스를 실체화할때는 3개만 넘겨주었다. self
파라미터를 빼먹었는데 이 self 파라미터가 매우 중요하다.
클래스의 self
는 어떠한 실체를 가르키는 단어이다. 그렇다면 당연히 클래스에서 self
는 클래스의 실체(instance)
를객체(Object)
를 가르킨다.
그러므로 Car class에서 self
는 Car class의 객체인 hyundai를 가르킨다.
class Car:
def __init__(self, maker, model, horse_power):
self.maker = maker
self.model = model
self.horse_power = horse_power
self
에 저장하는 것을 확인할 수 있다. 그리고 이렇게 객체에 maker,model,horse_power을 저장하는 이유는 나중에 다시 사용하기 위함이다.class Car:
def __init__(self, maker, model, horse_power):
self.maker = maker
self.model = model
self.horse_power = horse_power
def honk(self): #새로운 메소드 추가
return "빠라바라빠라밤"
honk
메소드에도 self가 추가된 것을 확인할 수 있는데 모든 메소드에는 self
파라미터가 첫번째로 추가되어야 한다. hyundai = Car("현대", "제네시스", 500) # 실체화
print(hyundai.honk()) # 객체에서 메소드 사용
.
를 사용해 객체를 호출한다. #완성
class Car:
def __init__(self, maker, model, horse_power):
self.maker = maker
self.model = model
self.horse_power = horse_power
def honk(self):
return f"{self.maker} 빠라바라빠라밤"
hyundai = Car("현대", "제네시스", 500) # 실체화
print(hyundai.honk()) # 객체에서 메소드 사용
honk
메서드에서 해당 객체의 회사 정보를 알고 싶다면, init 메소드에서 self객체에 대한 정보를 저장해 놓았기 때문에 위 코드처럼 사용하면 된다. object oriented programming(객체 지향 프로그래밍)
이라고 한다.