Meeting10 Classes and Object Oriented Programming s
Meeting10 Classes and Object Oriented Programming s
Meeting #10
AOU- M110 2
Procedural Programming
AOU- M110 3
Object-Oriented Programming (1 of 2)
Object-oriented programming: Whereas procedural programming is centered on creating
procedures (functions), object-oriented programming (OOP)is focused on creating objects
Object: An object is a software entity that contains data and procedures.
An object’s data attributes are simply variables that reference data.
The procedures that an object performs are known as methods.
An object’s methods are functions that perform operations on the object’s data attributes.
The object is, conceptually, a self-contained unit that consists of data attributes and
methods that operate on the data attributes.
• Data is known as data attributes and procedures are known as methods.
• Methods perform operations on the data attributes.
AOU- M110 4
Object-Oriented Programming (2 of 2)
AOU- M110 5
Classes
Before an object can be created, it must be designed by a programmer. The
programmer determines the data attributes and methods that are necessary,
then creates a class.
• Class: is a code that specifies the data attributes and methods of a
particular type of object. A class is considered as a factory to create objects.
• Like a blueprint* of a house. The blueprint itself is not a house but is a detailed
description of a house.
• A Python class uses variables (attributes) to define data fields and
methods to define behaviors.
• Instance: is an object created from a class
• Like a specific house built according to the blueprint.
• There can be many instances of one class. Each house is a separate instance of
the house described by the blueprint.
* blueprint :a design plan or other
technical drawing
AOU- M110 6
Classes
A way of thinking about the difference between a class and an object is to think of
the difference between a cookie cutter and a cookie. While a cookie cutter itself is
not a cookie, it describes a cookie. The cookie cutter can be used to make several
cookies, as shown in Figure 3. Think of a class as a cookie cutter, and the objects
created from the class as cookies.
AOU- M110 8
Classes
For example, if we design a class based on the states and behaviors of a
Person, then States can be represented as instance variables and
behaviors as class methods.
Instances
instance variables
instance
She studies 10
methods
He studies 15
AOU- M110 10
Class Definitions- example
• Example:
point.py
class Point:
x = 0 1 class Point:
y = 0 2 x = 0
3 y = 0
# main
p1 = Point()
p1.x = 2
p1.y = -5
AOU- M110 11
Using a Class
import class
– client programs must import the classes
they use
point_main.py
1 from Point import *
2
3 # main
4 p1 = Point()
5 p1.x = 7
6 p1.y = -3
7 ...
8
9 # Python objects are dynamic (can add fields
10 any time!)
p1.name = “Salim Hamad"
AOU- M110 12
Object Methods
def name(self, parameter, ..., parameter):
statement(s)
• self must be the first parameter to any object method.
• represents the "implicit parameter" (this in Java)
• Although you must specify self explicitly when defining the method, you
don’t include it when calling the method.
• Python passes it for you automatically.
class Point:
….. …
….. >>> p1.translate(1.5,2)
def translate(self, dx, dy):
self.x += dx
self.y += dy
...
AOU- M110 13
Calling Methods
• Example:
p1.translate(1, 5)
Point.translate(p, 1, 5)
AOU- M110 14
Class Methods: Example
class Person:
name = "I have no name :("
def sayName(self):
print("My name is...", self.name)
def main():
aPerson = Person()
aPerson.sayName()
aPerson.name = "Big Smiley :D"
aPerson.sayName()
main()
AOU- M110 15
What Is The ‘Self’ Parameter
• Reminder: When defining/calling methods of a class there is always
at least one parameter.
• This parameter is called the ‘self’ reference which allows an object to
access attributes inside its methods.
• ‘self’ is needed to distinguish the attributes of different objects of the
same class. No self! No self!
• Example:
bassem = Person() def sayName():
lisa = Person() print "My name is...",
lisa.sayName() name
AOU- M110 16
The Self Parameter: A Complete
Example
class Person:
name = "I have no name :("
def sayName(self):
print("My name is", self.name)
def main():
lisa = Person()
lisa.name = "Lisa Haddad, pleased to meet you."
bassem = Person()
bassem.name = "Bassem Hassan, who are you???!!!"
lisa.sayName()
bassem.sayName()
main()
AOU- M110 17
Recap: Accessing Attributes &
Methods
• Inside the class definition (inside the body of the class methods)
• Preface the attribute or method using the ‘self’ reference
class Person:
name = "No-name"
def sayName(self):
print("My name is", self.name)
AOU- M110 18
Class Definitions: Initializing The
Attributes
• Classes have a special method that can be used to initialize the starting
values of a class to some specific values.
• This method is automatically called whenever an object is created.
Two underscores without spaces between them
• Format:
class <Class name>:
def __init__(self, <other parameters>):
<body of the method> This design approach is
consistent with many languages
• Example:
class Person:
name = ""
def __init__(self):
self.name = "No name"
AOU- M110 19
Class Definitions
• Initializer method: automatically executed when an instance of the
class is created
• Initializes object’s data attributes and assigns self parameter to the object
that was just created
• Format: def __init__ (self):
• Usually, the first method in a class definition
class Point:
def __init__(self, ax,
ay):
self.x = ax
self.y = ay
class Coin:
# The _ _init_ _ method initializes the sideup data attribute with
'Heads’.
def _ _init_ _(self):
self.sideup = 'Heads'
AOU- M110 20
Class Definitions
• To create instances of a class, you call the class using class name (and
pass in whatever arguments its __init__ method accepts).
• Format: My_instance = Class_Name()
• To call any of the class methods using the created instance, use dot
notation
• Format: My_instance.method()
• Because the self parameter references the specific instance of the object, the
method will affect this instance
• Reference to self is passed automatically
AOU- M110 21
Initializing The Attributes Of A Class
• Because the ‘init()’ is a method, it can also be called with parameters which are then
used to initialize the attributes.
• Example:
# Attribute is set to a default in the class definition and then the
# attribute can be set to a non-default value in the init() method.
# (Not standard Python but a common approach with many languages)
class Person:
name = "Default name" # Create attribute here
def __init__(self, aName):
self.name = aName
OR
# Create the attribute in the init() method. (Approach often used in Python).
class Person:
def __init___(self, aName):
self.name = aName # Create attribute here
AOU- M110 22
Using The “Init()” Method-Example
class Person:
name = “No name"
def main():
aPerson = Person(“Jamal Nader")
print(aPerson.name)
main()
Output:
Jamal Nader
AOU- M110 23
Person Class Example
Write a Python class Person that represents a person with the attributes name,
age, and profession. The class should have an initializer method __init__() to
initialize the instance variables. It should also have two instance methods: show()
to display the name, age, and profession of the person, and work() to display the
person's name and profession.
AOU- M110 24
Person Class-Solution
class Person:
def __init__(self, aname, anage, aprofession):
# data members (instance variables)
self.name = aname
self.age = anage
self.profession = aprofession
AOU- M110 25
Computation class Example
You are requested to write a python program that does the following:
a. Create Computation class with a default constructor (without parameters)
allowing to perform various calculations on integers numbers.
b. Create a method called Factorial() in the above class which allows to
calculate the factorial of an integer, n.
c. Create a method called Sum() in the above class allowing to calculate the
sum of the first n integers 1 + 2 + 3 + .. + n.
d. Instantiate the class, prompt the user to enter an integer, and write the
necessary statements to test the above methods.
AOU- M110 26
Computation class - Solution
class Computation:
def __init__ (self):
self.n=0
# --- Factorial ------------
def factorial(self, n):
j=1
for i in range (1, n + 1):
j=j*i
return j
# --- Sum of the first n numbers ----
def sum (self, n):
j=0
for i in range (1, n + 1):
j=j+i
return j
x= Computation()
n=int(input("Enter an integer: "))
print("The factorial of the number",n, "is:",x.factorial(n))
print("The sum from the number",n, " to 1 is:",x.sum(n))
AOU- M110 27
Class Attributes vs Instance Attributes in Python
Class attributes are the variables defined directly in the class that are shared by all
objects of the class.
AOU- M110 28
Class Attributes vs Instance Attributes in Python
The following example demonstrates the use of class attribute count.
class Student: In this example, count is an attribute in the Student class.
count = 0 Whenever a new object is created, the value of count is
def __init__(self): incremented by 1.
Student.count += 1
std1=Student()
print(std1.count)
std2=Student()
print(std2.count)
print(Student.count)
Student.count=5
print(std1.count, std2.count)
AOU- M110 29
Coin Class Example
AOU- M110 31
Summary
• This lecture covered:
• Procedural vs. object-oriented programming
• Classes and instances
• Class definitions, including:
• The self parameter
• Data attributes and methods
• initializer
AOU- M110 32