-
파이썬을 배워 봅시다. 클래스와 객체 더 깊이 살펴보기 (1)사회 2024. 9. 25. 07:00728x90반응형
객체 지향 프로그래밍(OOP)의 기본 개념을 살펴보았으니,
이번에는 파이썬에서 실제로 OOP를 구현하는 방법을 더 구체적으로 다뤄볼게요.
클래스와 객체 더 깊이 살펴보기
파이썬에서 클래스와 객체를 생성하는 과정을 간단히 복습해 보겠습니다.
클래스는 객체를 만들기 위한 설계도이고,
객체는 그 설계도를 바탕으로 만들어진 실제 물건이라고 할 수 있어요.
pythonclass Person:def __init__(self, name, age):self.name = nameself.age = agedef greet(self):print(f"안녕하세요, 제 이름은 {self.name}입니다.")위 코드에서 Person 클래스는 name과 age라는 두 가지 속성을 가지고 있고,
greet라는 함수를 통해 자기소개를 할 수 있는 객체를 만들 수 있습니다.
이제 이 클래스를 사용해 객체를 만들어보겠습니다.
pythonperson1 = Person("철수", 25)person2 = Person("영희", 30)person1.greet() # "안녕하세요, 제 이름은 철수입니다."person2.greet() # "안녕하세요, 제 이름은 영희입니다."이처럼 같은 클래스를 사용해 여러 객체를 만들 수 있습니다.
각 객체는 자신만의 속성을 가지며,
같은 함수를 호출해도 속성에 따라 다른 결과가 나옵니다.
클래스 내부의 메서드
클래스 내부의 함수는 메서드라고 부릅니다.
메서드는 객체가 수행할 수 있는 동작을 정의하며,
클래스 안에 있는 함수는 기본적으로 첫 번째 인자로 self를 받아야 합니다.
이 self는 해당 메서드를 호출한 객체 자신을 가리킵니다.
예를 들어 greet 메서드는 self.name을 사용하여 객체의 이름을 출력합니다.
클래스 변수와 인스턴스 변수
객체의 속성은 두 가지로 나눌 수 있습니다: 클래스 변수와 인스턴스 변수입니다.
- 클래스 변수: 클래스 자체에 속하는 변수로, 모든 인스턴스가 공유합니다.
- 인스턴스 변수: 객체(인스턴스)마다 고유한 값을 가지는 변수입니다.
pythonclass Dog:species = "개" # 클래스 변수def __init__(self, name, breed):self.name = name # 인스턴스 변수self.breed = breed # 인스턴스 변수위 코드에서 species는 클래스 변수로,
모든 Dog 객체가 공유하는 값입니다.
반면에 name과 breed는 각각의 객체마다 다른 값을 가질 수 있는 인스턴스 변수입니다.
728x90반응형'사회' 카테고리의 다른 글
파이썬을 배워 봅시다. 상속, 다형성, 메서드 오버라이딩, 함수에 대하여 (1) (0) 2024.09.26 파이썬을 배워 봅시다. 클래스와 객체 더 깊이 살펴보기 (2) (4) 2024.09.25 파이썬을 배워 봅시다. 객체 지향 프로그래밍에 대하여 (2) (0) 2024.09.25 파이썬을 배워 봅시다. 객체 지향 프로그래밍에 대하여 (1) (0) 2024.09.24 파이썬을 배워 봅시다. 파이썬 기초: 모듈과 패키지 (2) (0) 2024.09.24