----------------- Object Oriented Programming Objects contain both data and functionality together vs. Procedural Programming which is simply a list of statements ----------------- ----------------- Class A Class defines a new data type Built in data types are: int float string list Lets build a data type for a point ----------------- ----------------- A point is two numbers (x,y) that is treated as a single object Before we created a list with two numbers p = [x,y] And we accessed it with p[0] and p[1] A class lets us define a new type with attributes (data) and methods (functions) ----------------- ----------------- class Point: # This represents a 2d point (x,y) def __init__(self,,y): self.x = x self.y = y Creating a new instance of the object time is called instantiating >>> myPoint = Point(1,2) init is a method that is invoked when an object is instantiated the first parameter of this method should be self, followed by the parameters to set up the attributes of Point ----------------- ----------------- We can set defaults with the init method class Point: # This represents a 2d point (x,y) def __init__(self,x=0,y=0): self.x = x self.y = y If Point() is instantiated without parameters, the instance will set its attributes to the default (0,0) >>> p1 = Point() # p1 now has (0,0) >>> p1 = Point(1,2) # p1 now has (1,2) ----------------- ----------------- __str__ method returns the string representation of the object class Point: # This represents a 2d point (x,y) def __init__(self,x=0,y=0): self.x = x self.y = y def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")" ----------------- ----------------- Besides __init__ and __str__ we can create any methods we like class Point: # This represents a 2d point (x,y) def __init__(self,x=0,y=0): self.x = x self.y = y def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")" def moveUpAndRight(self): self.x += 1 self.y += 1 ----------------- ----------------- Operator Overloading We can change the way built in operators work for our classes What happens if we try p = Point(1,2) q = Point(2,2) r = p + q >>> r = p + q TypeError: unsupported operand type(s) for +: 'Point' and 'Point' ----------------- ----------------- We need to overload the + operator to know how to add points using __add__ class Point: # This represents a 2d point (x,y) def __init__(self,x=0,y=0): self.x = x self.y = y def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")" def __add__(self,otherPoint): return Point(self.x + otherPoint.x, self.y + otherPoint.y) def moveUpAndRight(self): self.x += 1 self.y += 1 ----------------- ----------------- Exercise -----------------