반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- incr
- 퇴사통보
- 이분탐색
- 경력
- 성적평가
- 파라메트릭
- 백준
- @P0
- 13908
- Docker
- msSQL
- 매개변수탐색
- 백트래킹
- 오퍼레터
- compose
- 6987
- 물채우기
- Kafka
- 소프티어
- 기술면접
- boj #19237 #어른 상어
- 연결요소
- dfs
- 처우협의
- OFFSET
- BFS
- upper_bound
- 처우산정
- BOJ
- softeer
Archives
- Today
- Total
기술 블로그
class 연산자 재정의 본문
728x90
반응형
class 연산자 재정의
__init__
__add__
등등
p1 = p2 + p3의 형식
https://docs.python.org/3/reference/datamodel.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | import math class Point : def __init__(self, x, y) : self.x = x self.y = y def __add__(self, pt) : new_x = self.x + pt.x new_y = self.y + pt.y return Point(new_x, new_y) def __sub__(self, pt) : new_x = self.x - pt.x new_y = self.y - pt.y return Point(new_x, new_y) def __mul__(self, factor) : return Point(self.x * factor.x, self.y * factor.y) def length(self) : #length return math.sqrt(self.x**2 + self.y**2) def __len__(self) : #length return self.x**2 + self.y**2 def __getitem__(self, index) : if index == 0 : return self.x elif index == 1 : return self.y else : return -1 #def get_x(self) : # return self.x # #def get_y(self) : # return self.y def __str__(self) : return '({}, {})'.format(self.x, self.y) p1 = Point(3, 4) p2 = Point(2, 7) p3 = p1 + p2 p4 = p1 - p2 p5 = p1 * p2 print(p1) print(p2) print(p3) print(p4) print(p5) print(p1.length()) print(len(p1)) # p[0] -> x # p[1] -> y print('인덱스로 접근(getitem)', p1[0], p1[1]) | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class ComplexNumber : def __init__(self, num, i) : self.num = num self.i = i def __add__(self, cn) : return ComplexNumber(self.num + cn.num, self.i + cn.i) def __sub__(self, cn) : return ComplexNumber(self.num - cn.num, self.i - cn.i) def __mul__(self, cn) : return ComplexNumber(self.num * cn.num - self.i * cn.i, self.num * cn.i + self.i * cn.num) def __str__(self) : if self.i < 0 : return '{} - {}i'.format(self.num, -self.i) return '{} + {}i'.format(self.num, self.i) c1 = ComplexNumber(1, 2) c2 = ComplexNumber(3, 4) print(c1) print(c2) print(c1 + c2) print(c1 - c2) print(c1 * c2) | cs |
728x90
반응형
'Python' 카테고리의 다른 글
정규표현식 간단 연습 (0) | 2019.10.26 |
---|---|
정규표현식 (0) | 2019.10.26 |
class 상속 (0) | 2019.10.26 |
class staticmethod (0) | 2019.10.26 |
class self (0) | 2019.10.26 |