🔎 class
📌 선언
class FourCal:
pass
📌 생성자
- 형태
__(언더바 2개) + init + __(언더바2개)
class FourCal:
def __init__(self,first,second):
self.first=first
self.second=second
- 활용 방법
setdata 메서드와 달리, 선언할 때 바로 숫자를 넣어주어야 한다!
#main 부분
a=FourCal(2,3)
📌 함수(메서드) 사용법
- self의 사용
모든 def에 self가 첫 번째 매개변수로 항상 온다
C++과 매우 다른 점 중 하나임을 주의하자!
#class 부분
class FourCal:
def setdata(self,first,second):
self.first=first
self.second=second
#main 부분 -1
a=FourCal()
a.setdata(2,3)
#main 부분 -2(또 다른 표현법)
a=FourCal()
FourCal.setdata(a,2,3)
- main과 class의 관계
def setdata의 부분에 self,first,second는
self = a
first = 2
second = 3
의 순서로 전달된다!
- 변수
변수값은 class를 호출한 모든 객체에 동일함
#class
class FourCal:
name="jeong"
#main
a=FourCal()
b=FourCal()
a.name #👉🏻 jeong
b.name #👉🏻 jeong
📌 상속
- 형태
class MoreFourCal(FourCal):
def pow(self):
result=self.first**self.second
return result
- 사용 이유
클래스의 기능 확장을 위해
📌 메서드 오버라이딩(덮어쓰기)
- 형태
div 메서드는 부모 class 호출이 아닌 safeFourCal class가 호출된다!
class SafeFourCal(FourCal):
def div(self):
if self.second==0:
return 0
else:
return self.first/self.second
- 사용 이유
예외가 발생하는 경우에, 예외가 발생하지 않도록 하기 위하여!
'프로그래밍 - 기본 > Python' 카테고리의 다른 글
[점프 투 파이썬] 5장 - 예외처리 (0) | 2021.07.31 |
---|---|
[점프 투 파이썬] 5장 - 모듈 + 내장 함수 + 라이브러리 (0) | 2021.07.31 |
[점프 투 파이썬] 4장 - 연습문제 풀이 (0) | 2021.07.26 |
[점프 투 파이썬] 4장 - 파일 (0) | 2021.07.26 |