Classes

Python의 클래스(class)는 객체 지향 프로그래밍의 핵심 개념으로, 데이터와 그 데이터를 조작하는 메서드를 하나의 단위로 묶는 틀이다.

Python의 클래스는 코드의 재사용성을 높이고, 복잡한 프로그램을 구조화하는 데 도움을 준다. 객체 지향 프로그래밍의 원칙을 따르면서도 Python 특유의 간결함과 유연성을 제공한다.

클래스의 정의와 구조

클래스는 ‘class’ 키워드를 사용하여 정의한다:

일반적으로 클래스 이름은 대문자로 시작하는 카멜 케이스(CamelCase) 를 사용한다.

1
2
3
4
5
6
class ClassName:
    def __init__(self, parameters):
        self.attribute = parameters
    
    def method(self):
        # 메서드 내용

객체와 인스턴스

1
p = Person()  # Person 클래스의 인스턴스 생성

변수

1
2
3
4
5
class Dog:
    species = "Canis familiaris"  # 클래스 변수

    def __init__(self, name):
        self.name = name  # 인스턴스 변수
1
2
3
4
5
dog1 = Dog("Buddy")
dog2 = Dog("Molly")

print(dog1.species)  # 출력: Canis familiaris
print(dog2.species)  # 출력: Canis familiaris

상속(Inheritance)

상속을 통해 기존 클래스의 속성과 메서드를 새로운 클래스에서 재사용할 수 있다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Parent:
    def __init__(self):
        self.value = "부모 클래스"

    def show(self):
        print(self.value)

class Child(Parent):
    def __init__(self):
        super().__init__()  # 부모 클래스의 생성자 호출
        self.value = "자식 클래스"
1
2
3
child = Child()
child.show()
# 출력: 자식 클래스

다형성(Polymorphism)

다형성을 통해 같은 이름의 메서드가 다른 클래스에서 다르게 동작할 수 있다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

캡슐화(Encapsulation)

클래스 내부의 데이터를 외부로부터 보호하는 메커니즘이다. Python에서는 관례적으로 언더스코어를 사용하여 표현한다.

다중 상속(Multiple Inheritance)

Python은 여러 클래스로부터 상속받을 수 있는 다중 상속을 지원한다.

1
2
class Child(Mother, Father):
    pass

메서드

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class MyClass:
    class_variable = 0  # 클래스 변수

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

    def instance_method(self):
        print("인스턴스 메서드 호출")
        print(f"인스턴스 변수: {self.instance_variable}")

    @classmethod
    def class_method(cls):
        print("클래스 메서드 호출")
        print(f"클래스 변수: {cls.class_variable}")

    @staticmethod
    def static_method():
        print("정적 메서드 호출")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
obj = MyClass(10)
obj.instance_method()
# 출력:
# 인스턴스 메서드 호출
# 인스턴스 변수: 10

MyClass.class_method()
# 출력:
# 클래스 메서드 호출
# 클래스 변수: 0

MyClass.static_method()
# 출력:
# 정적 메서드 호출

참고 및 출처