MECN2012: Computing Skills and Software Development: Python - Object Oriented Programming
MECN2012: Computing Skills and Software Development: Python - Object Oriented Programming
Object Oriented
Programming
The Object Oriented approach to programming models the
world as classes of objects:
A square is an object in the polygon class
A dog is an object in the class mammals
Fido is an object
A method, which is
something the class can
do. Note that the first
argument is always self.
Two separate objects of the class Dog are created
fido.numLegs -= 1
# injured dog
print("total number of legs:", fido.numLegs + snoopy.numLegs)
# make him talk
fido.bark(3)
class Vehicle:
def getVehSpecs(self):
self.name = input("enter vehicle's name: ")
self.mass = float(input("enter " + self.name + "'s mass [kg]: "))
return
def energy(self):
return 0.5*self.mass*self.speed**2 # E = 0.5*m*v^2
highwaySpeed = 120/3.6
car1 = Vehicle()
car2 = Vehicle()
# m/s
# create 2 Vehicles
car1.getVehSpecs()
car2.getVehSpecs()
car1.getCrash(highwaySpeed)
car2.getCrash(highwaySpeed)
Constructors
We can control how an object is created by
including a definition of the __init__() method.
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
return
def disp(self):
print("x = ", x.r, " + ", x.i, "j", sep = "")
x = Complex(3.0, -4.5)
x.disp()
>>>
x = 3.0 + -4.5j
>>>
class Point:
X = 0
Y = 0
# default coord is the origin
def setCoords(self, x, y):
self.X = x
Changes the internal variables of the Point
self.Y = y
return
def getCoords(self):
Returns the list of [x, y] coordinates
return [self.X, self.Y]
class Circle:
centre = Point()
onCircle = Point()
# constructor method
**0.5
hulaHoop.move(1, 1)
print("the point on the circle has moved to:", hulaHoop.onCircle.getCoords(
>>>
the
the
the
the
the
>>>