Haliç University
Faculty of Engineering
CEN121
COMPUTER PROGRAMMING 1
Chapter 10
’’ Classes and Object-Oriented Programming’’
Lecturer: Asst.Prof. Zehra Merve Cinan
TOPICS
• Procedural and Object-Oriented Programming
• Classes
• Working with Instances
• Techniques for Designing Classes
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
2
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Procedural Programming
Procedural programming: writing programs made of
functions that perform specific tasks.
*Procedures typically operate on data items that are
separate from the procedures.
*Data items commonly passed from one procedure to
another.
*Focus: to create procedures that operate on the program’s
data.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
3
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Object-Oriented Programming
Object-oriented programming: focused on creating objects. Python is
an object oriented programming language. Almost everything in
Python is an object, with its properties and methods.object-oriented
Object: the entity that contains data and procedures.
*Data is known as data attributes and procedures are known as methods.
Methods perform operations on the data attributes.
Encapsulation: combining data and code into a single object.
Data hiding: object’s data attributes are hidden from code outside the
object.
*Access restricted to the object’s methods.
Protects from accidental corruption.
Outside code does not need to know the internal structure of
the object.
Object reusability: the same object can be used in different programs.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. *Example: 3D image object can be used for architecture and game
programming.
4
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
An Everyday Example of an Object
Data attributes: define the state of an object.
*Example: clock object would have second, minute,
and hour data attributes.
Public methods: allow external code to manipulate the
object.
*Example: set_time, set_alarm_time.
Private methods: used for the object’s inner workings.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
5
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Classes
Class: code that specifies the data attributes and methods
of a particular type of object. A Class is like an object
constructor or a "blueprint" for creating objects.
*Similar to a blueprint of a house or a cookie cutter.
Instance: an object created from a class.
*Similar to a specific house built according to the blueprint
or a specific cookie.
*There can be many instances of one class.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
6
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
To create a class, use the keyword class:
If we want to create a class named MyClass, with a
property named x:
class MyClass:
x = 5
print(MyClass)
Now we can use the class named MyClass to create
objects:
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
7
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Class Definitions
Class definition: the set of statements that define a class’s methods
and data attributes.
*Format: begin with class Class_name:
Class names often start with uppercase letter.
*Method definition like any other python function definition.
self parameter: required in every method in the class –
references the specific object that the method is working on.
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.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
8
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
class Person: The previous examples are classes and objects in their
def __init__(self, name, age): simplest form and are not really useful in real-life
self.name = name applications.
self.age = age
To understand the meaning of classes we have to understand
p1 = Person("John", 36) the built-in __init__() function.
print(p1.name) All classes have a function called __init__(), which is
print(p1.age) always executed when the class is being initiated.
Use the __init__() function to assign values to object
properties, or other operations that are necessary to do when
John the object is being created.
36 Note: The __init__() function is called automatically every
time the class is being used to create a new object.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
9
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Objects can also contain methods. Methods in objects are functions that belong to the object.
Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.
Let us create a method in the Person class:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Hello my name is John
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
10
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
The self parameter is a reference to the current instance of the class and is used to access variables that belongs to the class.
It does not have to be named self, you can call it whatever you like, but it has to be the first parameter of any function in the class.
If we want to use the words mysillyobject and abc instead of self:
class Person: class Person:
def __init__(self, name, age): def __init__(mysillyobject, name, age):
self.name = name mysillyobject.name = name
self.age = age mysillyobject.age = age
def myfunc(self): def myfunc(abc):
print("Hello my name is " + self.name) print("Hello my name is " + abc.name)
p1 = Person("John", 36) p1 = Person("John", 36)
p1.myfunc() p1.myfunc()
Hello my name is John
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
11
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
import random
# The Coin class simulates a coin that can
class Coin:
def __init__(self):
self.sideup = 'Heads'
def toss(self):
if random.randint(0, 1) == 0:
self.sideup = 'Heads'
else:
self.sideup = 'Tails' This side is up: Heads
def get_sideup(self): I am tossing the coin ...
return self.sideup
This side is up: Tails
def main():
my_coin=Coin()
print('This side is up:', my_coin.get_sideup())
print('I am tossing the coin ...')
my_coin.toss()
print('This side is up:', my_coin.get_sideup())
if __name__ == '__main__':
main()
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
12
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
13
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
To create a new instance of a class call the initializer method.
*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.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
14
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Hiding Attributes and Storing Classes in Modules
An object’s data attributes should be private.
*To make sure of this, place two underscores (__) in front of
the attribute name.
Example: __current_minute
Classes can be stored in modules.
*Filename for the module must end in .py.
*Module can be imported to programs that use the class.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
15
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
import random
# The Coin class simulates a coin that can
# be flipped.
class Coin:
# The _ _init_ _ method initializes the
# _ _sideup data attribute with ‘Heads’.
def __init__(self):
self.__sideup = 'Heads'
# The toss method generates a random number
# in the range of 0 through 1. If the number
# is 0, then sideup is set to 'Heads'.
# Otherwise, sideup is set to 'Tails'.
def toss(self):
if random.randint(0, 1) == 0:
self.__sideup = 'Heads'
else:
self.__sideup = 'Tails'
# The get_sideup method returns the value
# referenced by sideup.
def get_sideup(self):
return self.__sideup
This side is up: Heads
# The main function.
def main(): I am going to toss the coin ten times:
# Create an object from the Coin class.
my_coin = Coin() Tails
# Display the side of the coin that is facing up. Tails
print('This side is up:', my_coin.get_sideup())
Tails
# Toss the coin.
print('I am going to toss the coin ten times:') Heads
for count in range(10):
my_coin.toss() Tails
print(my_coin.get_sideup())
Tails
# Call the main function.
if __name__== '__main__': Heads
main()
Tails
Tails
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
Tails
16
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
17
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
The BankAccount Class – More About Classes
Class methods can have multiple parameters in addition to
self.
*For __init__, parameters needed to create an instance
of the class.
Example: a BankAccount object is created with a
balance.
• When called, the initializer method receives a
value to be assigned to a __balance
attribute.
*For other methods, parameters needed to perform required
task.
Example: deposit method amount to be deposited.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
18
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
19
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
The __str__ method
Object’s state: the values of the object’s attribute at a given
moment.
__str__ method: displays the object’s state.
*Automatically called when the object is passed as an
argument to the print function.
*Automatically called when the object is passed as an
argument to the str function.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
20
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
The __str__() function controls what should be returned
def __str__(self):
when the class object is represented as a string. return f"{self.name}({self.age})"
If the __str__() function is not set, the string p1 = Person("John", 36)
representation of the object is returned.
print(p1)
John(36)
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
21
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Working With Instances
Instance attribute: belongs to a specific instance of a class.
*Created when a method uses the self parameter to create
an attribute.
If many instances of a class are created, each would have
its own set of attributes.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
22
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
23
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Accessor and Mutator Methods
Typically, all of a class’s data attributes are private and
provide methods to access and change them.
Accessor methods: return a value from a class’s attribute
without changing it.
*Safe way for code outside the class to retrieve the value of
attributes.
Mutator methods: store or change the value of a data
attribute.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
24
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Passing Objects as Arguments
Methods and functions often need to accept objects as
arguments.
When you pass an object as an argument, you are actually
passing a reference to the object.
*The receiving method or function has access to the actual
object.
Methods of the object can be called within the
receiving function or method, and data attributes may
be changed using mutator methods.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
25
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Techniques for Designing Classes
UML diagram: standard diagrams for graphically depicting
object-oriented systems.
*Stands for Unified Modeling Language
General layout: box divided into three sections:
*Top section: name of the class.
*Middle section: list of data attributes.
*Bottom section: list of class methods.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
26
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Finding the Classes in a Problem
When developing the object-oriented program, the first goal is to identify classes.
*Typically involves identifying the real-world objects that are in the problem.
*Technique for identifying classes:
1. Get a written description of the problem domain.
2. Identify all nouns in the description, each of which is a potential class.
3. Refine the list to include only classes that are relevant to the problem.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
27
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
1. Get a written description of the problem domain:
*May be written by you or by an expert.
*Should include any or all of the following:
Physical objects simulated by the program.
The role played by a person.
The result of a business event.
Recordkeeping items.
2. Identify all nouns in the description, each of which is a potential class:
*Should include noun phrases and pronouns.
*Some nouns may appear twice.
3. Refine the list to include only classes that are relevant to the problem:
*Remove nouns that mean the same thing.
*Remove nouns that represent items that the program does not need to be concerned with.
*Remove nouns that represent objects, not classes.
*Remove nouns that represent simple values that can be assigned to a variable.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
28
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Identifying a Class’s Responsibilities
A classes responsibilities are:
*The things the class is responsible for knowing.
Identifying these helps identify the class’s data attributes.
*The actions the class is responsible for doing.
Identifying these helps identify the class’s methods.
To find out a class’s responsibilities look at the problem domain.
*Deduce required information and actions.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
29
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Summary
This chapter covered:
• Procedural vs. object-oriented programming
• Classes and instances
• Class definitions, including:
*The self parameter
*Data attributes and methods
*__init__ and __str__ functions
*Hiding attributes from code outside a class
• Storing classes in modules
• Designing classes
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved.
30
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL
Asst.Prof. Zehra Merve Cinan
Faculty of Engineering
Department of Electrical and Electronics Engineering,
8th Block, Floor: 2
Office: 2521
zehramervecinan@halic.edu.tr
CEN121- COMPUTER PROGRAMMING 1/ 2023-2024 FALL 31