본문 바로가기
수업(국비지원)/Python

[Python] 클래스에서 사용되는 특별한 함수들

by byeolsub 2023. 4. 24.
'''
2022-11-28 복습
함수 : def 예약어로 함수 정의
      return 값 : 함수를 종료하고 값을 전달
      매개 변수 : 함수를 호출 할 때 필요한 인자값 정의
         가변 매개변수 : 매개변수의 갯수를 지정안함. 0개 이상. *p  표현
         기본값 설정 : (n1=0,n2=0) : 0,1,2개의 매개변수 가능
예외처리 : try, except, finally, else, raise (예약어 의미들 잘 파악하기)
클래스 : 멤버변수, 멤버 함수, 생성자.
         인스턴스 변수 : self.변수명. 객체별로 할당되는 변수
         클래스 변수 : 클래스명.변수명. 해당 클래스의 모든 객체들의 공통변수
    self : 자기참조변수. 인스턴스 함수에 첫번째 매개변수로 설정. 반드시 써줘야 함.
    생성자 : __init__(self,...) : 객체 생성에 관여하는 함수
           클래스 내부에 생성자가 없으면 기본생성자를 제공
    상속 : class 클래스명(부모클래스1,부모클래스2,...) : 다중상속 가능
         오버라이딩 : 부모클래스의 함수를 자손클래스가 재정의
'''

 

📌 1. 클래스에서 사용되는 특별한 함수

'''
클래스에서 사용되는 연산자에 사용되는 특수 함수
+          __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) : 클래스의 객체를 출력할때 문자열로 리턴.
'''

# __xxx__ 형태인 함수.
class Line :
    length = 0 # 멤버변수
    def __init__(self,length) : # 생성자
        self.length = length
    def __repr__(self) :  # 객체를 문자열로 출력
        return "선길이:" + str(self.length)    
    def __add__(self,other) : # + 연산자 사용시 호출
        print("+ 연산자 사용:",end="")
        return self.length + other.length
    def __lt__(self,other) : # < 연산자 사용시 호출
        print("< 연산자 호출:")
        return self.length < other.length
    def __gt__(self,other) : # > 연산자 사용시 호출
        print("> 연산자 호출:") 
        return self.length > other.length
    def __eq__(self,other) : # == 연산자 사용시 호출
        print("== 연산자 호출:")  
        return self.length == other.length
        
line1 = Line(200) 
line2 = Line(100)
print("line1=",line1) # 결과 -> line1= 선길이:200
print("line2=",line2) # 결과 -> line2= 선길이:100      
print("두선의 합:",line1 + line2) # 결과 -> + 연산자 사용:두선의 합: 300
print("두선의 합:",line1.__add__(line2)) # 결과 -> + 연산자 사용:두선의 합: 300
if line1 < line2 :
    print("line2 선이 더 깁니다.")
elif line1 == line2 :
    print("line1과 line2 선의 길이는 같습니다.")
elif line1 > line2 :
    print("line1 선이 더 깁니다.")

 

'수업(국비지원) > Python' 카테고리의 다른 글

[Python] 파일 읽기  (0) 2023.04.24
[Python] 추상 함수, 모듈  (0) 2023.04.24
[Python] 멤버 변수 - 인스턴스 변수, 클래스변수 와 상속  (0) 2023.04.24
[Python] 클래스  (0) 2023.04.24
[Python] 예외 처리  (0) 2023.04.24