클래스와 객체, self에 대한 자세한 설명 (블로그 형식)
Python에서 객체 지향 프로그래밍(OOP)은 클래스와 객체를 활용하여 프로그램을 구성하는 중요한 개념입니다. 이번 글에서는 self가 무엇인지, 객체가 어떻게 생성되고 self가 어떻게 동작하는지에 대해 자세히 설명하겠습니다.
1. 객체 생성
먼저, 객체 지향 프로그래밍에서 객체란 클래스를 기반으로 생성된 실체입니다. 클래스를 설계도로 비유하고, 객체는 그 설계도를 바탕으로 실제로 만들어진 실체입니다.
코드 예시: 객체 생성
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 25)
여기서 person1은 Person 클래스의 객체입니다. Person("Alice", 25)는 객체를 생성하는 코드로, 이 코드에 의해 person1 객체는 name 속성에 "Alice", age 속성에 25를 가지게 됩니다.
설명:
- **Person**은 클래스입니다.
- **person1**은 클래스를 기반으로 만들어진 객체입니다. 객체는 Person 클래스의 인스턴스라고도 합니다.
- __init__ 메서드는 생성자로, 객체가 생성될 때 자동으로 호출되어 객체의 속성을 설정합니다.
- name="Alice"와 age=25는 person1 객체의 속성입니다.
2. 메서드 호출 시 self
클래스 내부의 메서드는 항상 **첫 번째 인자로 self**를 받습니다. 이 self는 클래스의 인스턴스 객체를 참조하는 변수입니다. 즉, 현재 메서드를 호출하는 객체 자신을 가리킵니다.
코드 예시: self 사용
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"Hi, I am {self.name}, and I am {self.age} years old.")
# 객체 생성
person1 = Person("Alice", 25)
# 메서드 호출
person1.introduce()
설명:
- self가 의미하는 것:
- self는 메서드를 호출할 때 자동으로 객체를 참조합니다.
- person1.introduce()를 호출하면, introduce 메서드의 **첫 번째 인자 self**는 person1 객체를 참조합니다.
- 이 때문에 self.name은 person1.name으로 해석되고, self.age는 person1.age로 해석됩니다.
- 실행 과정:
- person1.introduce()가 호출되면 self는 person1 객체가 됩니다.
- self.name은 person1.name, 즉 "Alice"가 되고, self.age는 25가 되어 출력됩니다.
- 최종 출력:
Hi, I am Alice, and I am 25 years old.
3. self가 실제로 가져오는 것
**self**는 클래스의 인스턴스를 가리킵니다. 즉, 메서드가 호출될 때 자기 자신을 가리키는 변수로, 클래스에서 **self**를 통해 객체의 속성에 접근할 수 있습니다.
실제 코드 흐름:
class Person:
def __init__(self, name, age):
self.name = name # self.name은 person1 객체의 'name' 속성
self.age = age # self.age는 person1 객체의 'age' 속성
def introduce(self):
print(f"Hi, I am {self.name}, and I am {self.age} years old.")
# person1 객체 생성
person1 = Person("Alice", 25)
# 메서드 호출
person1.introduce()
동작 흐름:
- person1 = Person("Alice", 25): Person 클래스에서 name="Alice"와 age=25 값을 받은 person1 객체가 생성됩니다.
- person1.introduce() 호출:
- introduce 메서드에서 **self**는 **person1**을 가리킵니다.
- self.name은 person1.name으로, **"Alice"**를 가리킵니다.
- self.age는 person1.age로, 25를 가리킵니다.
출력: "Hi, I am Alice, and I am 25 years old."
1. 객체 생성 (person1 = Person("Alice", 25))
먼저, person1 객체를 Person 클래스에서 생성할 때 __init__ 메서드가 호출됩니다.
person1 = Person("Alice", 25)
__init__ 메서드 실행
- **Person("Alice", 25)**는 Person 클래스의 객체를 생성하는 코드입니다.
- __init__는 생성자(initializer) 메서드로, 객체가 생성될 때 자동으로 호출됩니다. 여기서는 name과 age 값을 받아 self.name과 self.age 속성에 값을 저장합니다.
__init__ 메서드의 실행 흐름:
- __init__ 메서드에 **self, name="Alice", age=25**가 전달됩니다.
- self는 현재 생성 중인 객체를 참조합니다. 즉, person1 객체를 참조합니다.
- **name="Alice"**는 name 매개변수로 전달되고, **age=25**는 age 매개변수로 전달됩니다.
- self.name = name 코드에서:
- **self.name**은 person1 객체의 name 속성을 나타냅니다.
- name 매개변수 값 **"Alice"**가 **self.name**에 할당됩니다. 즉, person1.name = "Alice"가 됩니다.
- self.age = age 코드에서:
- **self.age**는 person1 객체의 age 속성을 나타냅니다.
- age 매개변수 값 **25**가 **self.age**에 할당됩니다. 즉, person1.age = 25가 됩니다.
- 이렇게 해서 person1 객체는 name 속성에 "Alice", age 속성에 25를 가지게 됩니다.
2. person1.introduce() 호출
이제 person1 객체가 생성되었고, introduce 메서드를 호출하는 코드입니다.
person1.introduce()
introduce 메서드 실행
- introduce 메서드는 self를 첫 번째 인자로 받습니다. 이때 **self**는 person1 객체를 가리킵니다.
- introduce 메서드에서 **self.name**과 **self.age**를 사용하여 person1 객체의 name과 age 속성에 접근하고, 이를 출력합니다.
introduce 메서드의 실행 흐름:
- **introduce(self)**가 호출될 때, **self**는 person1 객체를 가리킵니다. 즉, person1 객체의 속성인 name과 age에 접근할 수 있습니다.
- print(f"Hi, I am {self.name}, and I am {self.age} years old."):
- self.name은 **person1.name**을 가리키고, 그 값은 **"Alice"**입니다.
- self.age는 **person1.age**를 가리키고, 그 값은 25입니다.
전체 흐름 요약
- person1 = Person("Alice", 25):
- Person 클래스에서 person1 객체가 생성됩니다.
- __init__ 메서드가 호출되어 person1 객체의 **name**과 age 속성이 설정됩니다.
- person1.name = "Alice"와 person1.age = 25가 됩니다.
- person1.introduce():
- introduce 메서드가 호출되면, self는 person1 객체를 참조합니다.
- self.name은 "Alice", self.age는 25이므로, **print(f"Hi, I am Alice, and I am 25 years old.")**가 출력됩니다.
전체 코드 실행 예시
class Person:
def __init__(self, name, age):
self.name = name # self.name은 person1 객체의 'name' 속성
self.age = age # self.age는 person1 객체의 'age' 속성
def introduce(self):
# self는 person1 객체를 가리킴
print(f"Hi, I am {self.name}, and I am {self.age} years old.")
# person1 객체 생성
person1 = Person("Alice", 25)
# 메서드 호출
person1.introduce()
출력:
Hi, I am Alice, and I am 25 years old.
결론:
- person1 객체가 생성될 때, __init__ 메서드가 호출되어 person1.name과 person1.age를 설정합니다.
- person1.introduce()를 호출하면, self는 person1 객체를 참조하고, person1 객체의 속성에 접근하여 출력합니다.
- 이 메서드 호출의 흐름은 객체 지향 프로그래밍에서 **self**가 어떻게 객체를 참조하고, 속성에 접근하는지에 대한 좋은 예시입니다.
'기술블로그-Flask편' 카테고리의 다른 글
Flask의 기능 + Blueprint + Flask-Smorest 통한 작업섹션 구분 (0) | 2025.04.18 |
---|---|
Blueprint 이름은 Flask 내부에서 라우트와 뷰 함수를 구분하는 데 사용된다 (0) | 2025.04.18 |
API에 대한 이해 (0) | 2025.04.18 |
✅ Flask에서 JSON 응답 순서 보장하기 (OrderedDict 활용) (0) | 2025.04.18 |
✅ 추천 JSON Beautifier 크롬 확장 프로그램 (0) | 2025.04.18 |