객체 지향 프로그램(Objects Oriented Programming)
절차 지향 프로그래밍
로직
에 구조
를 더하기 위해 OOP를 사용코드의 구조화
class Car:
def __init__(self, model, price, color):
self.model = model
self.price = price
self.color = color
def drive(self, speed):
if speed > 100:
return "SPEEDING VIOLATION"
else:
return "DRIVE CAREFULLY"
Information Hiding
: 정보를 숨겨주는 기능으로써, 캡슐화되어 있는 코드들을 외부 접근으로부터 보호해서 객체가 훼손될 위험을 방지하는 기능Sub Class
)가 부모클래스(Base Class
, Super Class
)로부터 Property와 Method들을 상속 받을 수 있는 특성class Car:
def __init__(self, model, price, color):
self.model = model
self.price = price
self.color = color
def drive(self, speed):
if speed > 100:
return "SPEEDING VIOLATION"
else:
return "DRIVE CAREFULLY"
class Taxi(Car):
def take_passengers(self, passengers):
if passengers > 4:
return "5명 이상 못 탐"
else:
return "가자가자"
taxi1 = Taxi("기아", "3,000만원", "orange")
print(taxi1.take_passengers(7))
# 5명 이상 못 탐
print(taxi1.drive(120))
# SPEEDING VIOLATION 🔵
Taxi 클래스는 자신의 고유 Method를 사용할 수 있는 것은 물론 Car 클래스를 상속받았기 때문에 Car 클래스 안의 Property(model, price, color) 와 Method(drive) 모두를 사용할 수 있다🔵
상속성을 사용하면 자식클래스에서 불필요하게 다시 정의할 일 없이 부모클래스의 코드를 재사용가능하기 때문에 중복을 방지할 수 있다
override
: 부모클래스의 메소드를 그대로 상속받지 않고 재정의해서 사용할 수 있는 기능
class Car:
def __init__(self, model, price, color):
self.model = model
self.price = price
self.color = color
def drive(self, speed):
if speed > 100:
return "SPEEDING VIOLATION"
else:
return "DRIVE CAREFULLY"
class Taxi(Car):
def take_passengers(self, passengers):
if passengers > 4:
return "5명 이상 못 탐"
else:
return "가자가자"
def drive(self, speed):
if speed > 80:
return "택시는 80km/h 이상 금지"
else:
return "안전운전"
taxi1 = Taxi("기아", "3,000만원", "orange")
print(taxi1.take_passengers(7))
# 5명 이상 못 탐
print(taxi1.drive(90))
# 택시는 80km/h 이상 금지
Overloading
: 동일한 이름의 함수가 매개 변수에 따라서 다양하게 정의될 수 있는 것public class Math {
public int sum(int x, int y)
{
return (x + y);
}
public int sum(int x, int y, int z)
{
return (x + y + z);
}
public double sum(double x, double y)
{
return (x + y);
}
public static void main(String args[])
{
Math math = new Math();
System.out.println(math.sum(1, 2));
System.out.println(math.sum(3, 4, 5));
System.out.println(math.sum(7.7, 8.8));
}
}
Duck Typing
: “만약 어떤 것이 오리처럼 생겼고, 오리처럼 헤엄치고, 오리처럼 꽥꽥거린다면 그건 오리라고 봐야 한다"라는 오리 실험
에서 유래된 것으로 동일한 변수와 메소드를 가지고 있는 객체는 동일한 타입으로 간주하는 typing 방법Duck Typing
개념에 의하여 drive_car 함수 입장에서는 동일한 객체로 간주될 수 있다는 것이다.class Truck:
def drive(self):
print("Driving Truck")
def stop(self):
print("Stoping Truck")
class Bus:
def drive(self):
print("Driving Bus")
def stop(self):
print("Stoping Bus")
class RaceCar:
def drive(self):
print("Driving RaceCar")
def stop(self):
print("Stoping RaceCar")
def drive_car(car):
car.drive()
truck = Truck()
bus = Bus()
race_car = RaceCar()
drive_car(truck)
drive_car(bus)
drive_car(race_car)
# Driving Truck
# Driving Bus
# Driving RaceCar
Polymorphism
이 중요한 이유 : polymorphism을 통해서 포괄적인(generic) 인터페이스 제공이 가능해지기 때문이다. 위 duck typing 코드 예제에세도, drive_car
함수는 실제 input으로 들어오는 객체의 타입이나 구현 내용이나 실행 로직에 대해서 확인하거나 인지할 필요가 없다. drive
메소드만 가지고 있다면 실행이 가능하기 때문이다. 그러므로 polymorphism을 통해 굉장히 유연하고 간단한 인터페이스 및 로직 구현이 가능해진다.