기술 블로그

class 연산자 재정의 본문

Python

class 연산자 재정의

parkit 2019. 10. 26. 17:22
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(34)
p2 = Point(27)
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(12)
c2 = ComplexNumber(34)
 
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