Class
Class
A blueprint for objects. Defines attributes (fields) and behavior (methods). The basic unit of OOP.
Class
A blueprint for objects. Defines attributes (fields) and behavior (methods). The basic unit of OOP.
A Class is a blueprint or template for creating objects in object-oriented programming (OOP). When modeling real-world concepts or things in code, a class defines the attributes (data) and behaviors (functions) that the object will have.
A class consists of attributes (fields, member variables) and methods (member functions). For example, a "Car" class can have attributes such as color, speed, and fuel level and methods such as accelerate, stop, and refuel, and actual car objects (instances) are created from this blueprint.
The key characteristics of a class are encapsulation, inheritance, and polymorphism. Encapsulation bundles data and functions together and restricts outside access, inheritance extends an existing class to create a new one, and polymorphism allows different behaviors through the same interface.
In practice, classes are a core tool for improving code reusability and maintainability. Most modern programming languages such as Java, Python, C++, and TypeScript support classes, and in AI/ML they are also used to design models, datasets, and preprocessing pipelines as classes to create a well-organized code structure.
# 1. 기본 클래스 정의
class Animal:
"""동물 클래스 - 기본 설계도"""
# 클래스 변수 (모든 인스턴스가 공유)
kingdom = "Animalia"
# 생성자 메서드
def __init__(self, name, age):
# 인스턴스 변수 (각 객체마다 고유)
self.name = name
self.age = age
self._health = 100 # protected 변수 (관례)
# 인스턴스 메서드
def speak(self):
return "소리를 냅니다"
def info(self):
return f"{self.name}은(는) {self.age}살입니다."
# 2. 상속 (Inheritance)
class Dog(Animal):
"""개 클래스 - Animal을 상속받아 확장"""
def __init__(self, name, age, breed):
# 부모 클래스의 생성자 호출
super().__init__(name, age)
self.breed = breed
# 메서드 오버라이딩 (다형성)
def speak(self):
return "멍멍!"
# 새로운 메서드 추가
def fetch(self, item):
return f"{self.name}이(가) {item}을(를) 가져옵니다!"
class Cat(Animal):
"""고양이 클래스"""
def speak(self):
return "야옹~"
def scratch(self):
return f"{self.name}이(가) 긁습니다!"
# 3. 사용 예시
dog = Dog("바둑이", 3, "진돗개")
cat = Cat("나비", 2)
print(dog.info()) # 바둑이은(는) 3살입니다.
print(dog.speak()) # 멍멍!
print(dog.fetch("공")) # 바둑이이(가) 공을(를) 가져옵니다!
print(cat.speak()) # 야옹~
# 다형성 활용
animals = [dog, cat]
for animal in animals:
print(f"{animal.name}: {animal.speak()}")
"If you abstract the payment module as a Payment class and design it so that concrete classes such as CreditCardPayment and BankTransfer inherit from it, adding a new payment method becomes easy."
"The core of a class is encapsulation, inheritance, and polymorphism. Encapsulation hides internal implementation, inheritance reuses code, and polymorphism implements different behaviors behind the same interface. Following the Single Responsibility Principle from SOLID makes classes clear."
"This class is doing too much. Data validation and API calls are mixed together; if you split them into a Validator class and an ApiClient class, testing gets easier and maintenance gets more comfortable."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Giving one class too many responsibilities makes it hard to maintain. Follow the Single Responsibility Principle (SRP) and design each class to handle only one role.
When inheritance goes three or more levels deep, the code becomes hard to understand. Consider "composition over inheritance" first, and use inheritance only when necessary.
Use public, private, and protected appropriately to preserve encapsulation. Hide internal implementation as private and expose only the necessary interface as public.