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
63
64
65
66
67
68
69
70
71
|
#!/usr/bin/python3
# class <name>(parent)
# Here object is the 'global' parent class
# Parent classes are AKA superclass
class Coordinate(object):
# __init__ method, is the method called when
# an instance of this class is initialized
# 'self', is just python's formality to point
# an object data and/or object's method to itself.
# any other name can actually be used.
# Python will always pass the object itself as the first argument (hidden)
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
x_dist = (self.x - other.x) ** 2
y_dist = (self.y - other.y) ** 2
return (x_dist + y_dist) ** 0.5
# Special method for use when print(object) is called, it MUST return a
# string
def __str__(self):
return "<" + str(self.x) + "," + str(self.y) + ">"
# Operator Overloading
def __add__(self, other): # self + other
# Returns a new coordinate with the sum
return Coordinate(self.x + other.x, self.y + other.y)
def __sub__(self, other): # self - other
# Returns a new coordinate with the subtraction
return Coordinate(self.x - other.x, self.y - self.x)
# def __eq__(self,other) # self == other
# def __lt__(self,other) # self < other
# def __len__(self) # len(self)
# def __str__(self) # print(self)
# Notice (as in the the overloading example above), that we can make the Class
# (or the instanced objects), to return new instances of the class
# Example usage:
# Notice we don't need to pass the 1st (self) argument. Since the first argument
# is the object itself, python pass it automatically when instantiating the
# object.
# When you define a method, python will ALWAYS pass the actual object as the
# first argument for that method, and for convention, we use 'self' as name
a = Coordinate(3, 4)
b = Coordinate(0, 0)
# Remember, the first argument (the object itself), is passed automaticaaly
a.distance(b)
# We can use the class itself to call the methods, instead of an instance. But
# in this case, we need to provide the "self" argument, once we have no
# instanced object for python to pass it automatically
Coordinate.distance(a, b)
# isinstance() is a global function which return True/False if the object is an
# instance of t he specific class
isinstance(a, Coordinate)
|