클래스와 객체란?
# 클래스 Recipe 생성
class Recipe:
def cook(self):
print("오리가 완성되었습니다!")
# 객체 생성
pasta = Recipe()
pasta.cook() #출력: 요리가 완성되었습니다!
생성자(Init)와 속성
class Book:
# 인스턴스 속성: title, author
# 생성자: __init__()
def __init__(self, title, author):
self.title = title
self.author = author
def info(self):
print(f"책 제목: {self.title}, 저자: {self.author}")
book1 = Book("파이썬 입문", "홍길동")
book.info() # 출력: 책 제목: 파이썬 입문, 저자: 홍길동
메소드와 생성자(init)의 차이
# 생성자의 예제
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = color
# 메소드의 예제
def drive(self):
print(f"{self.color}색 {self.brand} 자동차가 달립니다")
상속 (Inheritance)
class Employee:
def __init__(self, name):
self.name = name
def work(self):
print(f"{self.name}이 일을 합니다.")
class Manager(Employee):
def __init__(self, name, department):
super().__init__(name)
self.department = department
def manage(self):
print(f"{self.name}이 {self.department} 부서를 관리합니다.")
m = Manager ("이영희", "영업")
m. work() # 출력: 이영희이 일을 합니다.
m. manage() # 출력: 이영희이 영업 부서를 관리합니다.