-
파이썬을 배워 봅시다. 클래스와 객체 더 깊이 살펴보기 (2)사회 2024. 9. 25. 08:00728x90반응형pythondog1 = Dog("바둑이", "진돗개")dog2 = Dog("초코", "푸들")print(dog1.species) # "개"print(dog2.species) # "개"print(dog1.name) # "바둑이"print(dog2.name) # "초코"
여기서 species는 모든 객체에서 동일하지만, name과 breed는 각기 다른 값을 가집니다.
메서드의 종류
파이썬에서는 메서드를 크게 세 가지로 나눌 수 있어요:
인스턴스 메서드, 클래스 메서드, 정적 메서드입니다.
- 인스턴스 메서드: 객체가 호출하는 메서드로, self를 첫 번째 인자로 받습니다.
- 객체의 상태(인스턴스 변수)를 변경하거나 참조할 수 있습니다.
-
pythondef instance_method(self):
-
# 인스턴스 변수에 접근하거나 변경 가능
-
pass
- 클래스 메서드: 클래스가 호출하는 메서드로, cls를 첫 번째 인자로 받습니다. @classmethod 데코레이터로 정의하며, 클래스 변수에 접근하거나 변경할 수 있습니다.
-
@classmethod
- python
-
def class_method(cls):
-
# 클래스 변수에 접근하거나 변경 가능
-
pass
- 정적 메서드: 클래스나 객체가 호출할 수 있는 메서드로, self나 cls를 받지 않습니다. @staticmethod 데코레이터로 정의하며, 클래스나 인스턴스와 무관한 기능을 구현할 때 사용합니다.
-
@staticmethod
- python
-
def static_method():
-
# 클래스나 인스턴스와 관계없이 동작
-
pass
정리
클래스와 객체는 파이썬에서 중요한 역할을 합니다.
클래스를 통해 코드를 재사용할 수 있고,
객체를 통해 각각의 데이터를 관리할 수 있습니다.
또한, 클래스와 인스턴스 변수를 구분하여 어떤 데이터가 객체마다 고유한지,
어떤 데이터가 모든 객체가 공유하는지 구분할 수 있죠.
객체 지향 프로그래밍의 원리를 파이썬에서 이해하면 복잡한 프로그램도 더 쉽게 구조화하고 유지할 수 있습니다.
다음으로는 상속과 다형성을 활용한 고급 객체 지향 개념을 더 자세히 다루겠습니다.
728x90반응형'사회' 카테고리의 다른 글
파이썬을 배워 봅시다. 상속, 다형성, 메서드 오버라이딩, 함수에 대하여 (2) (2) 2024.09.26 파이썬을 배워 봅시다. 상속, 다형성, 메서드 오버라이딩, 함수에 대하여 (1) (0) 2024.09.26 파이썬을 배워 봅시다. 클래스와 객체 더 깊이 살펴보기 (1) (0) 2024.09.25 파이썬을 배워 봅시다. 객체 지향 프로그래밍에 대하여 (2) (0) 2024.09.25 파이썬을 배워 봅시다. 객체 지향 프로그래밍에 대하여 (1) (0) 2024.09.24