Objects

Object Oriented Programming (OOP)

What are objects?

Example: [1,2,3,4] has type list

Advantages of OOP

Creating and using your own types with Classes

Define your own types

What are attributes?

Defining how to create an instance of a class

Actually creating an instance of a class

c = Coordinate(3, 4)  # create a new object of type Coordinate and pass in 3 and 4 to the __init__ method
origin = Coordinate(0, 0)
print(c.x)  # use the dot to access an attribute of instance c
print(origin.x)  # similarly, access an attribute of instance origin

What is a method?

Define a method for the Coordinate class

class Coordinate(object):
  def __init__(self, x, y):
    self.x = x
    self.y = y
  def distance(self, other): # self refers to the instance on which this method is called
                            # other is another parameter to the function call
    x_diff_sq = (self.x - other.x)**2  #dot notation to access data
    y_diff_sq = (self.y - other.y)**2
    return (x_diff_sq + y_diff_sq)**0.5

How to use a method

The following is an example of a method definition:
def distance(self, other):
  # code here

Using a class:

Print representation of an object

>>> c = Coordinate(3,4)
>>> print(c)
< __main__.Coordinate object at 0x7fa918510488

Defining your own print method

class Coordinate(object):
  def __init__(self, x, y):
    self.x = x
    self.y = y

  def distance(self, other):
    x_diff_sq = (self.x - other.x)**2
    y_diff_sq = (self.y - other.y)**2
    return (x_diff_sq + y_diff_sq)**0.5

  def __str__(self): # __str__ is the name of a special method
    return "<"+str(self.x)+","+str(self.y)+">"  #the return value must be a string

Wrapping your head around types and classes

Special Operators

Example: fractions

The power of OOP