class, class method 란?
2023. 2. 26. 15:56
클래스와 클래스 메서드는 Python 객체 지향 프로그래밍(OOP)의 핵심 개념으로,
사용자 정의 데이터 유형을 만드는 방법이다.
클래스는 데이터의 속성과 함수를 포함할 수 있고, 클래스 내에서 정의하고 method 를 통해 클래스가 수행할 동작과 작업을 추가로 정의할 수 있다.
#클래스 메소드 이해
class human():
'''인간'''
def __init__(self, name, weight):
self.name = name
self.weight = weight
def eat(self):
self.weight += 0.1
print("{}이가 먹어서 {}kg이 되었습니다".format(self.name, self.weight))
def walk(self):
self.weight -= 0.1
print("{}이가 걸어서 {}kg이 되었습니다".format(self.name, self.weight))
def speak(self, message):
print(message)
person = human('재홍', 78)
print(person.name, person.weight)
person.eat()
person.walk()
또한 클래스 메소드를 부모클래스와 자식클래스로 정의하여 함수를 공유(상속)할 수 있다.
반복적인 작업에 대해 class 로 정의하여 공통 속성과 동작을 공유하는 클래스 계층을 생성할 수 있고,
코드를 보다 쉽게 관리하고 유지할 수 있다.
전반적으로 Python의 클래스 함수는 객체지향 프로그래밍의 핵심 구성 요소이며 재사용 가능하고 유지 관리 가능한 모듈식 코드를 생성하기 위한 강력한 도구라 할 수 있다.
# 클래스 메서드 응용
class Animal():
def __init__(self, name):
self.name = name
def walk(self):
print('걷는다')
def greet(self):
print('{}이가 인사한다'.format(self.name))
# 자식클래스에서 부모클래스의 내용을 사용하고 싶을때 super() 사용
class human(Animal):
def __init__(self, name, hand):
super().__init__(name)
self.hand = hand
def wave(self):
print('{}을 흔들면서'.format(self.hand))
def greet(self):
self.wave()
super().greet()
person = human('재홍', '오른손')
person.greet()
'Python' 카테고리의 다른 글
머신 러닝 알고리즘 : (Regression) - 랜덤포레스트 (0) | 2023.03.09 |
---|---|
머신 러닝 알고리즘 : 선형 데이터 (Regression) (0) | 2023.03.06 |
random 패키지 (0) | 2023.02.26 |
math 패키지 (0) | 2023.02.26 |
for문 에서 2개의 인수를 받기 위한 enumerate 기능 (0) | 2023.02.26 |