Procedural Programming : procedures or functions are written that use or, operate on, data.
Object-oriented Programming (OOP): objects are created that are composed of both data and functionality
Benefits include:
managing increasing size and complexity of software applications
modifying complex code
In procedural programming, functions are the active agents
In OOP, objects are considered the active agent
Shifting the active agent to objects allows for more versatile functionality as well as code that is easier to write, maintain, and reuse
In Python, every value (str, int, float, list, … ) is an object.
Programs manipulate these objects by computing with them or asking them to perform methods.
An object has
a state
a collection of methods that it can perform
a turtle object as an example:
the state of a turtle includes such things as location , color, heading, …
turtle methods include .down()
, .forward()
, .left()
, .setheading()
, …
The Student Class
class Student:
def __init__(self, l_n, f_n, yr, gr):
self.l_name = l_n
self.f_name = f_n
self.year = yr
self.grades = gr
def get_l_name(self):
return self.l_name
def get_f_name(self):
return self.f_name
def get_grades(self):
return self.grades
def get_year(self):
return self.year
def g_ave(self):
if len(self.grades) > 0:
return sum(self.grades)/len(self.grades), len(self.grades)
else:
return 0.0, 0
def main():
s0001 = Student('Smith', 'Robert', 1, [3.7, 2.3, 4.0, 3.3])
print(s0001.get_l_name())
print(s0001.get_grades())
print(s0001.get_year())
gpa, n_courses = s0001.g_ave()
print(gpa, n_courses)
main()
The textbook uses the Point class as an example. It will be used in the two homework problems in assignment 29.
class Point:
""" Ploint class for representing and manipulating x, y coordinates. """
def __init__(self, initX, initY):
""" Create a new point at the given coordinates. """
self.x = initX
self.y = initY
def getX(self):
return self.x
def getY(self):
return self.y
def distanceFromOrigin(self):
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def main():
p = Point(3, 4)
print(p.getX())
print(p.distanceFromOrigin())
main()