24.11.29 - Class 문법 주요 개념

강연주·2024년 11월 29일

📚 TIL

목록 보기
104/186

Class 문법의 주요 개념

클래스 (Class)

클래스는 객체지향 프로그래밍(OOP)의 기본 단위로, 데이터와 메서드(데이터를 처리하는 함수)를 묶는 청사진. 클래스를 통해 새로운 객체(인스턴스)를 생성할 수 있다.

🖥️ python

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

인스턴스 (Instance)

클래스를 기반으로 생성된 객체를 인스턴스라고 한다. 각 인스턴스는 클래스의 구조를 따르지만 독립적인 값을 가질 수 있다.

🖥️ python

my_car = Car("Toyota", "Corolla")  # Car 클래스의 인스턴스 생성
print(my_car.brand)  # Toyota

생성자 (init)

클래스의 생성자 메서드로, 클래스가 초기화될 때 자동으로 호출된다. 주로 객체의 초기 속성을 설정하는 데 사용된다.

🖥️ python

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

person = Person("Alice", 30)

Getter와 Setter

getter와 setter는 클래스 속성에 안전하게 접근하고 수정하기 위해 사용.

  • Getter : 속성 값을 읽기
  • Setter : 속성 값을 설정하거나 검증하기
🖥️ python

class Account:
    def __init__(self, balance):
        self._balance = balance  # _를 붙여 비공개 변수로 처리

    @property
    def balance(self):
        return self._balance

    @balance.setter
    def balance(self, value):
        if value < 0:
            raise ValueError("Balance cannot be negative")
        self._balance = value

account = Account(1000)
print(account.balance)  # Getter 사용
account.balance = 500   # Setter 사용

상속 (Inheritance)

한 클래스가 다른 클래스의 속성과 메서드를 물려받는 기능.
코드 재사용성과 확장성을 높이는 데 유용하다.

  • 부모 클래스 (Superclass) : 기본 기능을 제공하는 클래스
  • 자식 클래스 (Subclass) : 부모 클래스를 확장하거나 기능을 수정한 클래스
🖥️ python

class Animal:
    def speak(self):
        return "Animal speaks"

class Dog(Animal):  # Animal 클래스를 상속
    def speak(self):
        return "Woof!"

dog = Dog()
print(dog.speak())  # Woof!

정적 메서드 (Static Method)

클래스와 관련이 있지만, 인스턴스나 클래스 속성에 접근하지 않는 메서드. 클래스 이름을 통해 호출되며, 메서드의 동작이 독립적일 때 사용된다.

🖥️ python

class MathOperations:
    @staticmethod
    def add(a, b):
        return a + b

print(MathOperations.add(3, 5))  # 8

클래스 메서드 (Class Method)

클래스 자체를 첫 번째 매개변수로 받는 메서드로, 클래스 속성을 수정하거나 클래스의 동작을 정의할 때 사용한다.


🖥️ python

class MyClass:
    count = 0

    @classmethod
    def increment_count(cls):
        cls.count += 1

MyClass.increment_count()
print(MyClass.count)  # 1

캡슐화 (Encapsulation)

클래스 내부 데이터를 외부에서 직접 접근하지 못하도록 제한하고, 필요한 경우 getter와 setter를 통해 제어한다. 이를 통해 데이터의 무결성을 보장할 수 있다.

다형성 (Polymorphism)

같은 이름의 메서드가 서로 다른 클래스에서 다르게 동작하도록 하는 기능입니다.

🖥️ python

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

animals = [Dog(), Cat()]
for animal in animals:
    print(animal.speak())  # 각각 "Woof!", "Meow!"
profile
아무튼, 개발자

0개의 댓글