Data Engineering/python

EP06 | Python 클래스와 객체지향 프로그래밍 (OOP)

ygtoken 2025. 3. 19. 22:37
728x90

이 글에서 다루는 개념

Python의 객체지향 프로그래밍(Object-Oriented Programming, OOP) 개념을 학습합니다.

  • 클래스(Class)와 객체(Object)의 개념
  • 생성자와 인스턴스 변수
  • 메서드와 self 키워드
  • 클래스 변수 vs 인스턴스 변수
  • 상속(Inheritance)과 메서드 오버라이딩

1️⃣ 클래스(Class)와 객체(Object)란?

Python에서 클래스는 **객체를 생성하는 틀(Template)**이며, 객체는 클래스에서 생성된 개별 인스턴스입니다.

# 클래스 정의
class Person:
    pass  # 아직 내용이 없음

# 객체 생성
p1 = Person()
p2 = Person()

print(type(p1))  # <class '__main__.Person'>

📌 클래스와 객체 특징

  • 클래스는 설계도, 객체는 실제 인스턴스
  • 같은 클래스로부터 여러 개의 객체를 생성 가능
  • self 키워드는 인스턴스 자신을 가리킴

2️⃣ 생성자와 인스턴스 변수

🔹 생성자 (__init__ 메서드)

클래스에서 객체가 생성될 때 자동으로 실행되는 특별한 메서드입니다.

class Person:
    def __init__(self, name, age):  # 생성자
        self.name = name  # 인스턴스 변수
        self.age = age

# 객체 생성
p1 = Person("Alice", 25)
p2 = Person("Bob", 30)

print(p1.name, p1.age)  # Alice 25
print(p2.name, p2.age)  # Bob 30

 

📌 생성자의 역할

  • 객체가 생성될 때 자동으로 실행
  • 인스턴스 변수를 초기화하는 역할

3️⃣ 메서드와 self 키워드

🔹 인스턴스 메서드

클래스 내에서 정의된 함수는 **메서드(Method)**라고 부릅니다.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):  # 메서드 정의
        return f"My name is {self.name} and I am {self.age} years old."

p1 = Person("Alice", 25)
print(p1.introduce())  # My name is Alice and I am 25 years old.

 

📌 self란?

  • self는 현재 인스턴스를 가리키는 키워드
  • 메서드 내부에서 객체의 속성(변수)이나 메서드에 접근할 때 사용

4️⃣ 클래스 변수 vs 인스턴스 변수

🔹 클래스 변수 (모든 객체가 공유)

클래스 변수는 클래스명.변수명 형식으로 접근하며, 모든 인스턴스가 공유합니다.

class Person:
    species = "Human"  # 클래스 변수

    def __init__(self, name):
        self.name = name  # 인스턴스 변수

p1 = Person("Alice")
p2 = Person("Bob")

print(p1.species)  # Human
print(p2.species)  # Human

 

📌 차이점 정리

  • 클래스 변수: 모든 인스턴스가 공유 (Person.species)
  • 인스턴스 변수: 객체마다 개별적으로 존재 (p1.name, p2.name)

5️⃣ 상속(Inheritance)과 메서드 오버라이딩

상속은 기존 클래스의 기능을 확장하여 새로운 클래스를 만드는 방법입니다.

class Animal:
    def sound(self):
        return "Some sound"

class Dog(Animal):  # Animal 클래스를 상속
    def sound(self):  # 메서드 오버라이딩
        return "Bark!"

d = Dog()
print(d.sound())  # Bark!

 

📌 상속의 장점

  • 코드의 재사용성을 높임
  • 기존 클래스의 기능을 유지하면서 새로운 기능 추가 가능

📌 실전 문제: 클래스와 객체 연습하기


문제 1: Person 클래스 작성

📌 Person 클래스를 만들고, 이름과 나이를 저장하는 생성자를 정의하세요.

# 🔽 여기에 코드 작성
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p1 = Person("Alice", 25)
print(p1.name, p1.age)  # Alice 25

문제 2: introduce() 메서드 추가

📌 이름과 나이를 출력하는 introduce() 메서드를 Person 클래스에 추가하세요.

class Person:
    # 🔽 여기에 코드 작성
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        return f"My name is {self.name} and I am {self.age} years old."

p1 = Person("Alice", 25)
print(p1.introduce())  # My name is Alice and I am 25 years old.

문제 3: 클래스 변수 활용

📌 모든 사람이 공유하는 species = "Human" 변수를 Person 클래스에 추가하세요.

class Person:
    # 🔽 여기에 코드 작성
class Person:
    species = "Human"  # 클래스 변수

    def __init__(self, name, age):
        self.name = name
        self.age = age

p1 = Person("Alice", 25)
print(p1.species)  # Human

문제 4: 상속을 활용한 클래스 생성

📌 Animal 클래스를 만들고, 이를 상속하는 Dog 클래스를 정의하세요.
📌 Dog 클래스에서 sound() 메서드를 오버라이딩하여 "Bark!"를 반환하도록 하세요.

class Animal:
    # 🔽 여기에 코드 작성
class Animal:
    def sound(self):
        return "Some sound"

class Dog(Animal):
    def sound(self):
        return "Bark!"

d = Dog()
print(d.sound())  # Bark!

 

728x90