0% found this document useful (0 votes)
2 views

[CreativeProgramming]Lecture11_OOP

The document covers Object-Oriented Programming (OOP), emphasizing its principles such as classes, objects, and the interaction between them. It explains the advantages of OOP, including easy modifications, increased efficiency, and simplified teamwork, along with practical examples like a car and coordinate systems. Additionally, it includes exercises for creating classes like Coordinate, Car, and TV, to reinforce the concepts discussed.

Uploaded by

allrounderguno
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

[CreativeProgramming]Lecture11_OOP

The document covers Object-Oriented Programming (OOP), emphasizing its principles such as classes, objects, and the interaction between them. It explains the advantages of OOP, including easy modifications, increased efficiency, and simplified teamwork, along with practical examples like a car and coordinate systems. Additionally, it includes exercises for creating classes like Coordinate, Car, and TV, to reinforce the concepts discussed.

Uploaded by

allrounderguno
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Creative Programming

Spring 2025
CUL1122 Lecture #11
Object-Oriented Programming
Today

❖Object-Oriented Programming
▪ Real World vs. Object-Oriented Programming
❖Classes and Objects
▪ Defining a Class
▪ Using Objects
❖Exercises: Working with Classes and Objects

3
Programming Paradigm: Internet Banking Example

❖Procedural Programming ❖Object-Oriented Programming

▪ Variables: Account number, account ▪ Attributes: Account number, account


holder, balance holder, balance
▪ Functions: Deposit, withdraw, ▪ Behaviors: Deposit, withdraw,
transfer transfer

4
Object-Oriented Programming
❖Object-oriented programming (OOP) is a programming paradigm that
focuses on the interaction between objects.
❖It provides a natural way to solve problems and is commonly used in
languages like Python, Java, C++, and C#.
❖Example: Starting a Car
▪ In this example, the two objects involved are
a person and a car.
▪ The interaction unfolds as follows:
➢The person gets into the car.
➢A command is given to start the car.
➢The car begins to run.

5
Programming Methodology

❖This approach views a program as a collection of components (objects)


and emphasizes the assembly of the necessary objects to construct the
program.
❖It simplifies the complexities of the real world by focusing on the key
features needed to define each object.
❖Process:
▪ 1) Object Creation
▪ 2) Object Assembly
▪ 3) Program Development

6
Complexity and Abstraction

❖Programming is much easier when problems are straightforward and


programs are manageable.
❖While complexity can impede effective programming, abstraction is the
key to overcoming it.
▪ Abstraction helps remove unnecessary details, allowing us to focus on what
truly matters.
❖Example of Abstraction: A Car Racing Game
▪ Car user interface: Right Pedal → “Accelerate,” Left Pedal → “Decelerate.”
▪ Users don’t need to understand the internal mechanics of the car.
▪ This interface remains consistent, whether the car is gasoline or electric.
7
Need for Object-Oriented Programming

❖Easy Modifications:
▪ When issues come up or new features need to be added, you can quickly
replace or add objects in the program.
❖Increased Efficiency and Productivity:
▪ Reusing existing objects can accelerate development and enhance overall
efficiency.
❖Simplified Teamwork:
▪ This approach supports distributed development for large-scale programs.

8
Objects

❖Simulating the Real World: Objects mimic real-world entities.


❖Grouping Similar Objects: This involves categorizing objects of the same
type.

Image Credits, clockwise from top: Image Courtesy Harald Wehner, in the public Domain. Image Courtesy MTSOfan, CC-BY-NC-SA. Image Courtesy Carlos Solana, license CC-
BY-NC-SA. Image Courtesy Rosemarie Banghart-Kovic, license CC-BY-NC-SA. Image Courtesy Paul Reynolds, license CC-BY. Image Courtesy Kenny Louie, License CC-BY

9
Objects

❖Simulating the Real World: Objects mimic real-world entities.


❖Grouping Similar Objects: This involves categorizing objects of the same
type.

Image Credits, clockwise from top: Image Courtesy Harald Wehner, in the public Domain. Image Courtesy MTSOfan, CC-BY-NC-SA. Image Courtesy Carlos Solana, license CC-
BY-NC-SA. Image Courtesy Rosemarie Banghart-Kovic, license CC-BY-NC-SA. Image Courtesy Paul Reynolds, license CC-BY. Image Courtesy Kenny Louie, License CC-BY

10
Composition of Objects

❖Objects represent data in an abstract way, ATTRIBUTES BEHAVIORS


Name Open Account
expressing generalized forms rather than Risk Tolerance Buy Stocks
Financial Goals Sell Stocks
specific instances. Diversification Close Account

❖1) Attributes
Investor
▪ These are the characteristics or states of the
objects.
❖2) Behavior/Methods
▪ These refer to the actions and functionalities
that objects can perform.
▪ They serve as interfaces for interaction between objects.

11
Implementation of OOP: Classes and Objects

❖Concept: Class
▪ A class acts as a template or blueprint that
defines the common attributes and behaviors
for all objects within that class.
❖Instance: Object
▪ An object is created from this template and
has its own unique attributes and behaviors.

12
Implementation of OOP: Classes and Objects

❖Components of a Class:
▪ Common attributes shared by all objects.
▪ Actions that all objects can perform.
❖Components of an Object:
▪ Specific values for each attribute that define its identity.
▪ A set of concrete actions the object can perform.

13
Example of Class and Object: Ford Car
Class: Ford Car Object: Ford Car 1

Attribute Attribute Identity


Color, Color: Orange,
Type, Type: Coupe,
Model, Model: Fucus,
Cylinder. Cylinder: 4

Behavior Behavior Object: Ford Car 2


Start, Accelerate, Reverse, Stop. Start, Accelerate,
Reverse, Stop Attribute Identity
Color: Yellow,
Type: Coupe,
Model: Mustang,
Cylinder: 6

Behavior
Start, Accelerate, Reverse, Stop 14
Object-Oriented Programming Phases
❖1) Define Class
▪ This involves bundling an object’s attributes and behaviors into a single package.
▪ You start by defining the class name and then listing its attributes and methods.
❖2) Create Objects
▪ To use a class, you need to create an instance, which represents a specific case
of that class.
▪ This requires specifying the class attributes in concrete terms to instantiate the
object.
❖3) Implement Object Interaction
▪ In this phase, the focus is on expressing interactions between objects through
their associated methods.
15
Problem Solving Using Object-Oriented Programming

❖Example Problem: Starting a Car


▪ The person object sends a command to start the car object.

Object: Person 1
Object: Ford Car 1
Attribute Identity
Name: Jennie Attribute Identity
Height: 5’ 4’’ Color: Orange,
Age: 21 Type: Coupe,
Model: Fucus,
Behavior Cylinder: 4
Speak, Listen, Eat, Run, Walk
Behavior
Start, Accelerate, Reverse, Stop

16
Defining a Class: Step 1 - Specifying the Name and Parent Class

❖To create a class, use the class keyword followed by the class name and
the parent class name.
❖Similar to functions, the code within the class definition must be
indented.
❖Example: The Coordinate Class
▪ In this case, object is the parent class, and Coordinate becomes the child class.
▪ This means that the Coordinate class inherits all the attributes of the Python
object class.

class Coordinate(object):
# Attributes and methods 17
Defining a Class: Step 2 - Implementing the __init__() Method

❖The __init__() method initializes the attributes (identity) when objects


are created.
▪ For instance, a coordinate object requires specific X and Y values.
class Coordinate(object):
def __init__(self, x, y): self refers to the object itself.
self.x = x The dot (.) operator is used for attribute access.
self.y = y

❖In every method, the first parameter represents the object itself and is
denoted as self.
❖You use the dot (.) operator to access each attribute or method of the
object.
18
Defining a Class: Step 2 - Implementing the __init__() Method

❖When an object is created, the __init__() method is automatically called


to initialize the object’s attributes.
▪ The first parameter, self, is automatically passed by Python, even if you don’t
explicitly specify it.
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y

c = Coordinate(3, 4) Creating a coordinate object with the coordinates (3, 4).


origin = Coordinate(0, 0)
print(c.x) The dot (.) operator is used for attribute access.
print(origin.x) 19
Defining a Class: Step 3 - Adding Custom Methods

❖Add specific operations or functions to manipulate the class.


▪ For example, in a coordinate class, you would include a method for calculating
the distance between coordinates.
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
Adding a method for measuring the
def distance(self, other): distance between coordinates.
x_diff_sq =(self.x - other.x) ** 2
y_diff_sq =(self.y - other.y) ** 2
return (x_diff_sq + y_diff_sq) ** 0.5

20
Defining a Class: Step 4 - Redefining the __str__() Method

❖By default, the print() function displays the object’s memory address.
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
x_diff_sq = (self.x - other.x) ** 2
y_diff_sq = (self.y - other.y) ** 2
return (x_diff_sq + y_diff_sq) ** 0.5
>>> c = Coordinate(3, 4)
>>> print(c) Printing memory address not useful for user.
<__main__.Coordinate object at 0x7fa918510488> 21
Defining a Class: Step 4 - Redefining the __str__() Method
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
x_diff_sq =(self.x - other.x) ** 2
y_diff_sq =(self.y - other.y) ** 2
return (x_diff_sq + y_diff_sq) ** 0.5
def __str__(self): Redefining to print useful object information.
return '('+str(self.x)+', '+str(self.y)+')'
>>> c = Coordinate(3, 4)
>>> print(c)
(3, 4)
22
Using Objects: Step 1 – Creating an Object

❖For creating an object, specify the class name along with its attributes.
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
x_diff_sq =(self.x - other.x) ** 2
y_diff_sq =(self.y - other.y) ** 2
return (x_diff_sq + y_diff_sq) ** 0.5
def __str__(self):
return '('+str(self.x)+', '+str(self.y)+')'
>>> c = Coordinate(3, 4)
23
Using Objects: Step 2 – Invoking a Method

❖To call a method on an object, use the dot (.) operator.


class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
x_diff_sq =(self.x - other.x) ** 2
y_diff_sq =(self.y - other.y) ** 2
return (x_diff_sq + y_diff_sq) ** 0.5
def __str__(self):
return '('+str(self.x)+', '+str(self.y)+')'

>>> c = Coordinate(3, 4)
>>> zero = Coordinate(0, 0)
>>> print(c.distance(zero))
24
Advantages of Object-Oriented Programming
❖Encapsulation:
▪ Manage attributes and their related methods as a single package.
▪ Example: account number, holder, balance, deposit, withdrawal, transfer.
❖Divide-and-Conquer Development:
▪ Develop and evaluate each class separately.
▪ This approach reduces complexity by organizing code into modules, making it
easier to create complex programs.
❖Code Reuse with Classes:
▪ Most Python modules are designed as classes.
▪ Inheritance allows child classes to inherit and modify attributes or methods
from parent classes as needed.
25
Lab 11
Exercise 1: Coordinate Class in 2D Space (Assignment 3)

❖Create a Coordinate class to represent points in two-dimensional space


using x and y values. Your class should include:
▪ An initialization method __init__ to store x and y coordinates.
▪ A string method __str__ to return a readable description of the coordinate.
▪ Three custom methods:
➢distance() – calculates the distance between two coordinates.
➢midpoint() – returns the midpoint between two coordinates.
➢slope() – computes the slope between two coordinates (you may display a message for
vertical lines where the slope is undefined).

27
Exercise 1: Coordinate Class in 2D Space (Assignment 3)

❖Verification Required:
▪ Create two Coordinate objects for the points (0, 0) and (3, 4).
▪ Then:
➢Print their coordinate information.
➢Print the distance, midpoint, and slope between them.

28
Exercise 2: Car Class
❖Create a Car class to represent basic features and behaviors of a car.
Your class should include:
▪ Attributes:
➢model: the name of the car model
➢speed: the current speed of the car
➢price: the price of the car
▪ Methods:
➢getSpeed(): returns the current speed
➢getPrice(): returns the price
➢isFaster(other): returns True if the current car is faster than the other car
➢isMoreExpensive(other): returns True if the current car is more expensive than the other
car
29
Exercise 2: Car Class

❖Verification Required:
▪ Create three Car objects with the following data:
➢Model: “BMW X5”, Speed: 222, Price: 90295
➢Model: “Toyota Cololla”, Speed: 200, Price: 28145
➢Model: “Jeep Wrangler”, Speed: 210, Price: 89390
Jeep Wrangler
▪ Then: 210 km/h
$89,390
➢Print each car’s model, price, and speed.
Toyota Cololla
➢Compare their speeds and prices using isFaster() BMW X5 200 km/h
222 km/h
and isMoreExpensive() methods. $90,295 $28,145

30
Exercise 2: Car Class

❖Output:

31
Exercise 3: TV Class with Controls and Limits

❖Create a TV class that simulates a television with adjustable channel


and volume settings. Your class should include:
▪ Attributes:
➢on: A Boolean indicating whether the TV is on
➢channel: The current channel number
➢maxChannel: The maximum channel number
➢volumeLevel: The current volume level
➢maxVolumeLevel: The maximum volume level

32
Exercise 3: TV Class with Controls and Limits
▪ Methods:
➢Power control: getOn(), turnOn(), turnOff()
➢Channel control: getChannel(), setChannel(), channelUp(), channelDown()
➢Volume control: getVolume(), setVolume(), volumeUp(), volumeDown()

❖Behavioral Notes:
▪ Channel and volume operations should only work when the TV is turned on.
▪ Channel and volume levels should not fall below 1 or exceed their maximum
values.

33
Exercise 3: TV Class with Controls and Limits

❖Verification Required:
▪ Create a TV object with the initial channel set to 1 and volume level set to 1.
▪ Then,
➢Turn the TV on.
➢Adjust the channel and volume several times, including attempts to exceed both the
lower and upper limits.
➢Print the final channel and volume levels to verify they remain within valid bounds.

34
수고하셨습니다!

35

You might also like