파이썬에서 클래스는 사용자 정의 자료형으로, 멤버변수와, 멤버함수(메서드)로 이루어져 있고, 클래스를 사용하기 위해서는 객체로 찍어내서 사용한다. 객체는 각자 고유한 성격을 가지고, 조금 변형 된다고 하더라도 다른 객체나, 클래스에 영향을 주지 않는다. 또한 다중상속이 가능하다.
class 클래스명:
def 메서드명(self,매개변수1,매개변수2,...):
pass
def __inif__(self):
pass
객체명1 = 클래스명()
객체명1.메서드명(입력인수1,입력인수2)
객체명2 = 클래스명()
클래스명.메서드명(객체명2, 입력인수1, 입력인수2,...)
=> 클래스명은 대문자로 시작한다.
=> 객체는 클래스를 담는다. 특정객체는 특정클래스의 인스턴스라고도 부른다.
=> self는 자기참조변수로 인스턴스 함수의 매개변수로 설정해야한다. self에는 객체명을 호출해준다.
=> def __inif__(self): 는 기본생성자로 객체가 생성 될 때 자동으로 호출되는 메서드다.
클래스 만들기 : 사칙연산 클래스
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
a = FourCal(111,2)
print(a.add())
print(a.mul())
b = FourCal(721,7)
print(FourCal.add(b))
print(b.sub())
print(b.div())
클래스의 상속 : 사칙연산클래스 상속받아서 제곱기능 추가하기
기존의 클래스를 변경하지 않고 기능을 추가하거나, 기존 기능을 변경 할 때 사용한다. 기존 클래스가 라이브러리 형태로 제공되거나, 수정이 허용되지 않는 상황에서는 상속을 사용해야 한다.
class 클래스명(상속할 기존 클래스 명)
class MoreFourCal(FourCal):
def pow(self):
result = self.first ** self.second
return result
c=MoreFourCal(4, 2)
print(c.pow())
print(c.add())
print(c.sub())
메서드 오버라이딩 : 나누기메서드 기능 수정하기(0으로 나눌 경우 오류 안나게)
클래스를 상속받아서 기존 메서드를 동일한 이름으로 다시 작성해서 덮어쓰는것을 오버라이딩이라고 한다. 오버라이딩을 하면 호출 시 부모클래스의 메서드가 아닌 상속받아서 오버라이딩 된 메서드가 호출된다.
class 클래스명(상속할 기존 클래스 명)
def 기존메서드명(self):
수정 할 내용 작성
class SafeFourCal(FourCal):
def div(self):
if self.second == 0:
return 0
else:
return self.first / self.second
d=SafeFourCal(4, 0)
print(d.div())
# 0
e=FourCal(4, 0)
print(e.div())
# ZeroDivisionError: division by zero
클래스 변수
객체변수(인스턴스변수)는 다른 객체들에 영향을 받지 않고 독립적으로 그 값을 유지한다. 반면 클래스변수는 변수값을 변경하면 클래스로 만든 모든 객체에 공유된다는 특징이 있다. 즉 클래스변수는 모든 객체의 공통 변수이다.
생성자에서 변수 사용하기
클래스변수 : 클래스명.멤버변수명
인스턴스변수 : self.인스턴스변수명
class FourCal:
num1 = 0 #인스턴스변수
num2 = 0 #인스턴스변수
totalcnt = 0 #클래스변수
count = 0 #인스턴스변수
name = "계산기 클래스" #클래스변수
def __init__(self, first, second):
self.num1 = first
self.num2 = second
FourCal.totalcnt += 1 #클래스변수
self.count = FourCal.totalcnt #인스턴스변수
def printInfo(self):
print(FourCal.name)
print(self.count,"번째 객체입니다")
return "%d번째객체까지 생성 됐습니다." %FourCal.totalcnt
def add(self):
result = self.num1 + self.num2
return result
def mul(self):
result = self.num1 * self.num2
return result
def sub(self):
result = self.num1 - self.num2
return result
def div(self):
result = self.num1 / self.num2
return result
a = FourCal(9,3)
print(a.printInfo())
'''
계산기 클래스
1 번째 객체입니다
1번째객체까지 생성 됐습니다.
'''
b = FourCal(5,2)
FourCal.name = "사칙연산 계산기 클래스"
print(b.printInfo())
'''
사칙연산 계산기 클래스
2 번째 객체입니다
2번째객체까지 생성 됐습니다.
'''
print(a.printInfo())
'''
사칙연산 계산기 클래스
1 번째 객체입니다
2번째객체까지 생성 됐습니다.
'''
클래스변수 name을 사칙연산 계산기 클래스로 변경하면 이미 생성 된 객체들의 name변수 값까지 전부 변경이 된다.
또한 클래스변수 totalcnt 또한 변한값으로 변경이 된다. 인스턴스변수인 count는 객체마다 독립적으로 그 값을 유지한다.
클래스에서 연산자에 사용되는 특수 함수
+ __add__(self, other)
– __sub__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
// __floordiv__(self, other)
% __mod__(self, other)
** __pow__(self, other)
& __and__(self, other)
| __or__(self, other)
^ __xor__(self, other)
< __lt__(self, other)
> __gt__(self, other)
<= __le__(self, other)
>= __ge__(self, other)
== __eq__(self, other)
!= __ne__(self, other)
생성자 : __init__(self,...) : 클래스 객체 생성시 요구되는 매개변수에 맞도록 매개변수 구현
출력 : __repr__(self) : 클래스의 객체를 출력할때 문자열로 리턴.
class FourCal():
num = 0 #인스턴스변수
totalcnt = 0 #클래스변수
count = 0 #인스턴스변수
def __init__(self,num):
self.num = num
FourCal.totalcnt += 1 #클래스변수
self.count = FourCal.totalcnt #인스턴스변수
def __repr__(self):
return "숫자"+str(self.num)+str(self.count)+"번째 객체입니다\n"\
+str(FourCal.totalcnt)+"번째 객체까지 생성 됐습니다."
def __add__(self, other):
print("+ 연산자 호출 : ",end="")
return self.num + other.num
def __sub__(self, other):
print("- 연산자 호출 : ",end="")
return self.num - other.num
def __mul__(self, other):
print("* 연산자 호출 : ",end="")
return self.num * other.num
def __truediv__(self, other):
print("/ 연산자 호출 : ",end="")
return self.num / other.num
a = FourCal(4)
b = FourCal(10)
print(a) #__repr__
'''
1번째 객체입니다
2번째 객체까지 생성 됐습니다.
'''
print(b) #__repr__
'''
2번째 객체입니다
2번째 객체까지 생성 됐습니다.
'''
print(a+b)
# + 연산자 호출 : 14
print(a.__sub__(b))
# - 연산자 호출 : -6
print(b*a)
# * 연산자 호출 : 40
print(b.__truediv__(a))
# / 연산자 호출 : 2.5
클래스안에 추상메서드
부모클래스의 멤버 중 추상메서드가 있으면, 자손에서 반드시 오버라이딩 해야 한다.
class 클래스명:
def 추상함수명(self) :
raise NotImplementedError
class Parent :
def method(self) : #추상함수
raise NotImplementedError
class Child(Parent) :
def method(self) :
print("자손클래스에서 오버라이딩 함")
ch1=Parent()
ch1.method()
# 오류발생 NotImplementedError
ch2 = Child()
ch2.method()
# 자손클래스에서 오버라이딩 함
'프로그래밍언어 > Python' 카테고리의 다른 글
[Python] 예외 처리 (0) | 2021.12.29 |
---|---|
[Python] 모듈 (0) | 2021.12.29 |
[Python] 파일 읽고 쓰기 (0) | 2021.12.28 |
[Python] 함수 (0) | 2021.12.28 |
[Python] 컴프리헨션(Comprehension) (0) | 2021.12.27 |