-
Notifications
You must be signed in to change notification settings - Fork 248
Expand file tree
/
Copy pathnumeric_finished.py
More file actions
46 lines (34 loc) · 944 Bytes
/
numeric_finished.py
File metadata and controls
46 lines (34 loc) · 944 Bytes
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
# Example file for Advanced Python: Language Features by Joe Marini
# give objects number-like behavior
# Refer to:
# https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "<Point x:{0},y:{1}>".format(self.x, self.y)
# implement addition
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
# implement subtraction
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
# implement in-place addition
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self
# Declare some points
p1 = Point(10, 20)
p2 = Point(30, 30)
print(p1, p2)
# Add two points
p3 = p1 + p2
print(p3)
# subtract two points
p4 = p2 - p1
print(p4)
# Perform in-place addition
p1 += p2
print(p1)