01. 객체 지향 프로그래밍(OOP)
- 점차 코드가 복잡해짐에 따라 간단한 관게를 유지하는 것이 필요해짐. 이것이 객체 지향 프로그래밍이 필요해진 이유.
- 자율 주행 자동차를 프로그래밍할 때 다양한 기능들이 핋요하다. 예로, 카메라, 네비게이션, 연료 관리 방식 등. 각각의 기능들을 모듈화 하였다면, 추후 다른 프로젝트를 진행할 때 재사용이 가능하다.
- 예로, 1인 식당을 운영한다고 가정하면 혼자서 서빙, 요리, 청소까지 모두 다 해내야 한다. 이럴 경우 큰 사이즈의 식당을 운영하는 것은 불가능하다. 하지만, 각각의 역할을 맡은 사람들을 고용하여 매니징만 담당하게 된다면 큰 식당도 커버가 가능하다.
- 이것이 절차 지향 프로그래밍과 객체 지향 프로그래밍의 큰 차이점이다.
02. OOP 사용법 : 클래스와 객체
- waiter 라는 객체를 만들고자 한다면, 크게 "가진 것(has)"과 "하는 것(does)" 로 나눌 수 있다.
is_holding_plate = True
tables_responsible = [4,5,6]
def take_order(table, order):
def take_payment(amount):
- 속성(attribute) : 특정 객체에 소속된 변수
- 메소드(methods) : 모델로 만든 특정 객체가 할 수 있는 일
- 객체(object) : 데이터 + 함수를 결합하는 것
- 같은 객체를 여러 개 만들어 낼 수 있다. 즉, 여러 명의 웨이터를 만들어 낼 수 있음.
- 클래스(class) : 객체가 될 수도, 변수가 될 수도 객체 지향 프로그래밍에선 자유롭게 사용이 가능하다. 즉, A 클래스를 B클래스에서는 변수로 사용이 가능하다.
03. 객체를 만들고 속성과 메소드에 접근하기
car = CarBlueprint()
- 클래스로부터 객체를 생성화 하려면 위와 같이 표현함.
from turtle import Turtle, Screen
timmy = Turtle()
print(timmy)
timmy.shape("turtle")
timmy.color("coral")
timmy.forward(100)
my_screen = Screen()
print(my_screen.canvheight)
my_screen.exitonclick()
04. 객체 속성 변경 및 메소드 호출 연습
from prettytable import PrettyTable
table = PrettyTable()
table.add_column("Pokemon Name",["Pikachu","Squirtle","Charmander"])
table.add_column("Type", ["Electric","Water","Fire"])
print(table)
table.align = "l"
print(table)
05. quiz _ CoffeeMachine
from menu import Menu
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
money_machine = MoneyMachine()
coffee_maker = CoffeeMaker()
menu = Menu()
is_on = True
while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}): ")
if choice == "off":
is_on = False
elif choice == "report":
coffee_maker.report()
money_machine.report()
else:
drink = menu.find_drink(choice)
if coffee_maker.is_resource_sufficient(drink) and money_machine.make_payment(drink.cost):
coffee_maker.make_coffee(drink)