파이썬 클래스 - 객체, 생성자, 속성, 메소드, 상속

김지수·2025년 6월 3일

클래스와 객체란?

  • 클래스: 설계도
  • 객체: 설계도를 바탕으로 만들어진 실체
  • 속성: 클래스 안의 변수
  • 메소드: 클래스 안의 함수
# 클래스 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)

  • 부모 클래스의 속성과 메소드를 자식 클래스가 물려받음
  • 자식 클래스에서 부모의 생성자를 호출하려면 super() 사용
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()  # 출력: 이영희이 영업 부서를 관리합니다.
        
profile
오늘 배운 것을 기록하며, 나만의 지식으로 만들어가는 성장 일지 💪🍀

0개의 댓글