python

18편 Python 고급 문법: 클래스와 객체의 고급 기능

파이썬 티쳐 2024. 11. 22. 09:53

1. 클래스 상속과 다형성

1.1 상속(Inheritance)의 심화

상속은 자식 클래스가 부모 클래스의 속성과 메서드를 물려받는 기능입니다. 이를 통해 코드의 재사용성을 높이고, 공통된 기능을 부모 클래스에 정의하여 자식 클래스에서 불필요한 중복을 피할 수 있습니다.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        raise NotImplementedError("Subclass must implement this method")

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

1.2 자식 클래스에서 부모 클래스 메서드 오버라이딩

오버라이딩은 자식 클래스가 부모 클래스의 메서드를 재정의하여, 부모 클래스의 메서드를 덮어씁니다.

class Bird(Animal):
    def speak(self):
        return f"{self.name} says Chirp!"

1.3 다형성(Polymorphism)

다형성은 다양한 객체가 동일한 메서드를 호출하지만, 각 객체가 고유한 방식으로 동작할 수 있게 합니다.

animals = [Dog("Buddy"), Cat("Whiskers"), Bird("Tweety")]
for animal in animals:
    print(animal.speak())

2. 클래스 메서드와 정적 메서드

2.1 클래스 메서드(@classmethod)의 정의와 사용법

클래스 메서드는 클래스 자체를 첫 번째 인자로 받으며, 클래스 변수에 접근할 수 있습니다.

class MyClass:
    count = 0

    def __init__(self):
        MyClass.count += 1

    @classmethod
    def get_count(cls):
        return cls.count

2.2 정적 메서드(@staticmethod)의 정의와 사용법

정적 메서드는 클래스나 인스턴스에 의존하지 않는 독립적인 메서드입니다.

class MathUtility:
    @staticmethod
    def add(x, y):
        return x + y

print(MathUtility.add(5, 3))  # 출력: 8

3. 클래스와 객체를 활용한 프로그램

3.1 상속을 활용한 간단한 게임 캐릭터 클래스 작성

class Character:
    def __init__(self, name, attack, defense):
        self.name = name
        self.attack = attack
        self.defense = defense

    def attack_enemy(self):
        return f"{self.name} attacks with {self.attack} power!"

class Warrior(Character):
    def __init__(self, name):
        super().__init__(name, attack=15, defense=10)

    def special_move(self):
        return f"{self.name} performs a powerful sword slash!"

class Mage(Character):
    def __init__(self, name):
        super().__init__(name, attack=20, defense=5)

    def special_move(self):
        return f"{self.name} casts a fireball spell!"

3.2 클래스 메서드와 정적 메서드를 활용한 객체 관리 시스템 구현

Student 클래스에 클래스 메서드와 정적 메서드를 사용하여 학생 수를 관리하고, 성인 여부를 확인하는 기능을 구현합니다.

class Student:
    students = []

    def __init__(self, name, age):
        self.name = name
        self.age = age
        Student.students.append(self)

    @classmethod
    def count_students(cls):
        return len(cls.students)

    @staticmethod
    def is_adult(age):
        return age >= 18

# 객체 생성
s1 = Student("Alice", 17)
s2 = Student("Bob", 20)

# 클래스 메서드로 학생 수 확인
print(f"총 학생 수: {Student.count_students()}")  # 출력: 총 학생 수: 2

# 정적 메서드로 나이 확인
print(f"Alice는 성인인가? {Student.is_adult(s1.age)}")  # 출력: False
print(f"Bob은 성인인가? {Student.is_adult(s2.age)}")    # 출력: True