고래밥 이야기
Python_class 본문
다음을 참고하였습니다.
05-1 클래스 - 점프 투 파이썬 (wikidocs.net)
05-1 클래스
초보 개발자들에게 클래스(class)는 넘기 힘든 장벽과도 같은 존재이다. 독자들 중에도 클래스라는 단어를 처음 접하는 이들도 있을 것이다. 그러면 도대체 클래스가 무엇인지, 클…
wikidocs.net
용어 설명
class(클래스) : 과자 틀
object(객체) : class로 만든 것 (과자 틀에 의해서 만들어진 과자)
instance(인스턴스) : 거의 객체와 개념이 같다. 하지만 객체는 그 자체로 쓰이고, 인스턴스는 클라스와 같이 쓰인다. 예시로 a = class()라면, 'a는 객체이다.' 'a는 class의 인스턴스이다'로 쓰인다.
method(매서드) : 클래스 안에 구현된 함수
- 객체를 통해 클래스의 매서드를 호출하기 위해서는 a.setdata(4,2)와 같이 도트(.) 연산자를 사용해야 한다.
constructor(생성자) : 객체가 생성될 때, 자동으로 호출되는 메서드를 의미한다.
#1. method인 setdata를 사용하여 초깃값을 설정
class FourCal:
def setdata(self, first, second):
self.first = first
self.second = second
a = FourCal()
a.setdata(2,4)
#2. 객체가 만들어짐과 동시에 초깃값을 설정 여기서 __init__는 생성자이다.
class FourCal:
def __init__(self, first, second):
self.first = first
self.second = second
a = FourCal(2,4)
성질
클래스의 상속(inheritance) : 어떤 클래스를 만들 때, 다른 클래스의 기능을 물려받을 수 있게 만드는 것이다. 보통 상속은 기존 클라스를 변경하지 않고 기능을 추가하거나 기존 기능을 변경하려고 할 때(method overriding(메서드 오버라이딩)) 사용한다.
# class 클래스 이름(상속할 클래스 이름)
# 1. 기존의 기능을 추가할 때
class FourCal:
def __init__(self, first, second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
def mul(self):
result = self.first * self.second
return result
def sub(self):
result = self.first - self.second
return result
def div(self):
result = self.first / self.second
return result
class MoreFourCal(FourCal): # MoreFourCal은 기존의 FourCal의 method와 method pow를 사용할 수 있다.
def pow(self):
result = self.first ** self.second
return result
# 2. 기존의 기능을 변경할 때 (method overriding(메서드 오버라이딩))
class FourCal:
def __init__(self, first, second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
def mul(self):
result = self.first * self.second
return result
def sub(self):
result = self.first - self.second
return result
def div(self):
result = self.first / self.second
return result
class SafeFourCal(FourCal):
def div(self):
if self.second == 0: # 나누는 값이 0인 경우 0을 리턴하도록 수정
return 0
else:
return self.first / self.second
'잡다 > 잡다 그 잡채' 카테고리의 다른 글
Python_def (0) | 2022.11.09 |
---|---|
Python_inner product (1) | 2022.11.09 |
Python_module (0) | 2022.11.09 |
Python_The import system (0) | 2022.11.09 |
python_%timeit (0) | 2022.10.31 |
Comments