Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96168
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
15
class Point:
16
"""Represents a point in 2-D space.
17
18
attributes: x, y
19
"""
20
def __init__(self, x=0, y=0):
21
self.x = x
22
self.y = y
23
24
def __str__(self):
25
return '(%g, %g)' % (self.x, self.y)
26
27
def __add__(self, other):
28
"""Adds a Point or tuple."""
29
if isinstance(other, Point):
30
return self.add_point(other)
31
elif isinstance(other, tuple):
32
return self.add_tuple(other)
33
else:
34
msg = "Point doesn't know how to add type " + type(other)
35
raise TypeError(msg)
36
37
def add_point(self, other):
38
"""Adds a point."""
39
return Point(self.x + other.x, self.y + other.y)
40
41
def add_tuple(self, other):
42
"""Adds a tuple."""
43
return Point(self.x + other[0], self.y + other[1])
44
45
46
47
def main():
48
p1 = Point(1, 2)
49
p2 = Point(3, 4)
50
print(p1)
51
print(p2)
52
print(p1 + p2)
53
print(p1 + (3, 4))
54
55
if __name__ == '__main__':
56
main()
57
58
59