diff options
Diffstat (limited to 'mit/oop/myclasses.py')
| -rw-r--r-- | mit/oop/myclasses.py | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/mit/oop/myclasses.py b/mit/oop/myclasses.py new file mode 100644 index 0000000..9dc57bc --- /dev/null +++ b/mit/oop/myclasses.py @@ -0,0 +1,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) |
