# import packages
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns; sns.set()
Python is an object-oriented programming language, which means that it provides features that support object-oriented programming, which has these defining characteristics:
Before, we would define the class and a function as such
class Time:
"""Represents the time of day.
attributes: hour, minute, second
"""
def print_time(time):
print('%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second))
This observation is the motivation for methods; a method is a function that is associated with a particular class. Methods are semantically the same as functions, but there are two syntactic differences:
class Time:
"""Represents the time of day.
attributes: hour, minute, second
"""
def print_time(time):
print('%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second))
start = Time() # this is an instance of a Time object
start.hour = 9
start.minute = 45
start.second = 00
print_time(start)
09:45:00
Now, let's use method syntax to call this function
start.print_time()
09:45:00
Note: print_time
is the name of the method , and start
is the object the method is invoked on, which is called the subject.
Inside the method, the subject is assigned to the first parameter, so in this case start is assigned to time
.
By convention, the first parameter of a method is called self
, so it would be more common to write print_time
like this:
class Time:
def print_time(self):
print('%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second))
def increment_time(self, seconds):
return self
# put the definition of increment_time from last notebook
The init method (short for “initialization”) is a special method that gets invoked when an object is instantiated. Its full name is __init__
(two underscore characters, followed by init, and then two more underscores). An init method for the Time class might look like this:
class Time:
"""Represents the time of day.
attributes: hour, minute, second
"""
def __init__(self, hour=0, minute=0, second=0):
# assign self.hour as hour (passed in)
self.hour = hour
self.minute = minute
self.second = second
def print_time(self):
print('%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second))
start2 = Time(3,2,11)
start2.print_time()
03:02:11