Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Object-oriented programming language

The document outlines a curriculum for an Object-Oriented Programming (OOP) module at Debre Markos Polytechnic College, covering topics such as basic syntax, data types, and OOP principles like encapsulation and inheritance. It includes practical coding examples in Python, Java, and C++, and emphasizes best practices in coding and documentation. The module spans 80 hours and is designed to enhance programming skills through structured learning and hands-on activities.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Object-oriented programming language

The document outlines a curriculum for an Object-Oriented Programming (OOP) module at Debre Markos Polytechnic College, covering topics such as basic syntax, data types, and OOP principles like encapsulation and inheritance. It includes practical coding examples in Python, Java, and C++, and emphasizes best practices in coding and documentation. The module spans 80 hours and is designed to enhance programming skills through structured learning and hands-on activities.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Debre Markos Polytechnic College

Department of Web Development and Database


Administration

Level III

Module Title: Object-oriented programming language


Module code: EIS WDDBA4 M01 1123
Nominal duration: 80 Hours

1
Table of Contents

Unit One: Identification of content needs..................................................................Error! Bookmark not defined.


1.1 Introduction to Object Oriented Programming language........................Error! Bookmark not defined.
1.2 Basic language syntax rules and Best practices......................................Error! Bookmark not defined.
1.3 Data-types, Operators and Expression....................................................Error! Bookmark not defined.
1.4 Sequence, Selection and Iteration constructs..........................................Error! Bookmark not defined.
1.5 Modular Programming Approach...........................................................Error! Bookmark not defined.
1.6 Arrays and Arrays of objects...................................................................Error! Bookmark not defined.
Unit Two: Basic OO principles.....................................................................................Error! Bookmark not defined.
2.1 Primitive Member Variables in Class Implementation...........................Error! Bookmark not defined.
2.2 Flexible Object Construction..................................................................Error! Bookmark not defined.
2.3 User-Defined Aggregation in Class Design............................................Error! Bookmark not defined.
2.4 Navigating Hierarchical Inheritance.......................................................Error! Bookmark not defined.
2.5 Code Extension through Versatile Polymorphism..................................Error! Bookmark not defined.
Unit Three: Debug code................................................................................................Error! Bookmark not defined.
3.1 Integrated Development Environment (IDEs)........................................Error! Bookmark not defined.
3.2 Program Debugging Techniques.............................................................Error! Bookmark not defined.
Unite Four: Document activities....................................................................................Error! Bookmark not defined.
4.1 Crafting Maintainable Object-Oriented Code.........................................Error! Bookmark not defined.
4.2 Documentation of Object-oriented Programming...................................Error! Bookmark not defined.
Unite Five: Test code.......................................................................................................Error! Bookmark not defined.
5.1. Simple Tests in Object-Oriented Programming.................................Error! Bookmark not defined.
5.2. Embracing Corrections in Code and Documentation.........................Error! Bookmark not defined.

Acronym

ADD -------------------------------------------------------------- Addition / Additive

API --------------------------------------------------------------- Application Programming Interface

CSV ---------------------------------------------------------------Comma-Separated Values

IDE-----------------------------------------------------------------Integrated Development Environment

OO------------------------------------------------------------------Object-Oriented

OOP---------------------------------------------------------------- Object-Oriented Programming

VS-------------------------------------------------------------------Visual Studio

2
Unit One - Identification of Content Needs

1. Introduction to Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) enhances productivity and manages program complexity


by focusing on objects that encapsulate data and behavior. Popular OOP languages include C++,
Java, and Python.

Key Principles of OOP:

 Objects & Classes: Objects represent real-world entities, and classes define their structure.
 Data Abstraction: Essential features are exposed while implementation details remain hidden.
 Encapsulation: Data and methods are bundled within a single unit, ensuring controlled access.
 Inheritance: New classes (subclasses) derive attributes and behaviors from existing classes
(superclass), promoting reusability.
 Polymorphism: Allows a single interface for different data types, facilitating flexibility and code
reusability.

2. Basic Language Syntax Rules and Best Practices


A. Naming Conventions

 Use meaningful and descriptive names for classes, methods, and variables.
 Follow naming standards such as CamelCase for classes and camelCase for methods and
variables.

Example (Java):

class ShoppingCart {
void addItem(String item) {
// Code logic
}
}

B. Encapsulation
Encapsulation restricts access to object components using access modifiers like private,
protected, and public.
Example (Python):
class BankAccount:
def __init__(self):
self.__balance = 0 # Private attribute

def deposit(self, amount):


if amount > 0:
self.__balance += amount

def get_balance(self):
return self.__balance

3
C. Inheritance

Inheritance allows a new class to use attributes and methods from an existing class.

Example (Python):

class Animal:
def make_sound(self):
pass

class Dog(Animal):
def make_sound(self):
return "Bark"

D. Polymorphism

Allows objects of different classes to be treated as objects of a common superclass.

Example (Java):

class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}

E. Design Patterns & Best Practices


Singleton Pattern: Ensures a class has only one instance.
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
Single Responsibility Principle (SRP): Each class should have one specific function.
class Logger:
def log(self, message):
print("Log: ", message)

class PaymentProcessor:
def process_payment(self, amount):
print("Processing payment of", amount)

Following these OOP principles ensures modular, reusable, and maintainable code structures.

4
1.3 Data Types, Operators, and Expressions

Object-Oriented Programming (OOP) Overview

Object-Oriented Programming (OOP) is a programming paradigm based on objects. Objects


contain:

 Attributes (variables): Store data.


 Methods (functions): Define behavior.

OOP uses classes as blueprints to create objects.

Comparison of OOP in Different Languages

A. Java

 Class-Based: Everything is encapsulated in classes.


 Strongly Typed: Requires explicit type declarations.
 Uses Interfaces: For abstraction and enforcing class contracts.

B. C++

 Hybrid Language: Supports both procedural and OOP paradigms.


 Manual Memory Management: Requires explicit allocation and deallocation of memory.
 Multiple Inheritances: A class can inherit from multiple base classes.

C. JavaScript

 Prototype-Based: Objects inherit directly from other objects.


 Dynamically Typed: No need for explicit type declarations.
 Supports Functional Programming: Along with OOP.

D. Python (Focus Language)

 Clear Syntax: Easy to read and write.


 Dynamically Typed: No need to declare variable types.
 Extensive Libraries: Rich standard and third-party libraries.
 Interpreted Language: Executes code line-by-line, simplifying debugging.

1.3.1 Start Coding with Python


Getting Started

Before coding in Python, it’s essential to understand fundamental programming concepts such
as:

5
 Variables
 Data Types
 Conditionals
 Loops
 Functions

Setting Up Python

1. Install Python: Download the latest version from the official Python website.
2. Choose an IDE: Use an Integrated Development Environment (IDE) like:
o PyCharm
o Visual Studio Code (VS Code)
o Jupyter Notebook
o IDLE (comes with Python)
3. Configure Python: Ensure Python is properly installed and running on your system.

Visual Studio Code (VS Code)

 A powerful and lightweight code editor by Microsoft.


 Features:
o IntelliSense for smart code completion
o Built-in debugger
o Git integration
o Customizable with extensions for linting, formatting, and testing
 Cross-platform (Windows, macOS, Linux).

1.3.2 Python Data Types, Operators, and Expressions


A. Python Data Types
Python data types are categorized into:
1. Core Data Types
o Numbers (int, float, complex)
o Strings (text data)
2. Boolean Data Type
o Holds True or False values.
3. Compound Data Types
o Lists: Ordered, mutable collections. []
o Tuples: Ordered, immutable collections. ()
o Dictionaries: Key-value pairs. {}
o Sets: Unordered collections of unique elements. {}

Core Data Types

1. Numbers
 Integers (int): Whole numbers without decimals.
o Example: x = 10
 Floating Point (float): Numbers with decimals.

6
o Example: y = 3.14
 Complex Numbers (complex): Written in the form x + yj.
o Example: z = 2 + 3j
2. Strings (str)
 Strings are sequences of characters enclosed in single (' ') or double (" ") quotes.
 Multiline strings use triple quotes (''' or """).
 Strings support indexing and slicing.
Example:
python
text = "Hello, Python!"
print(text[0]) # Access first character
print(text[0:5]) # Slice first 5 characters

Boolean Data Type


 A Boolean variable holds either True or False.
 Used for logical operations and conditions.
Example:
python
is_active = True
print(type(is_active)) # Output: <class 'bool'>

Compound Data Types

1. Lists (list)
 Ordered, mutable collection.
 Items can be of different data types.
 Created using square brackets [].
Example:
python
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Adds new item
print(fruits)

2. Tuples (tuple)
 Ordered, immutable collection.
 Created using parentheses ().
Example:
python
colors = ("red", "green", "blue")
print(colors[1]) # Access second element

3. Dictionaries (dict)
 Unordered collection of key-value pairs.
 Created using curly braces {}.
Example:
python
student = {"name": "John", "age": 21, "course": "CS"}
print(student["name"]) # Output: John

7
4. Sets (set)
 Unordered collection of unique elements.
 Created using curly braces {}.
Example:
python
CopyEdit
numbers = {1, 2, 3, 4, 4, 5}
print(numbers) # Output: {1, 2, 3, 4, 5} (removes duplicate)

B. Operators in Python
Operators perform operations on variables and values.
1. Arithmetic Operators
Used for mathematical operations:
Operator Description Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
// Floor Division x // y (Removes decimal)
% Modulus x % y (Remainder)
** Exponentiation x ** y (Power)

2. Relational (Comparison) Operators


Used for comparisons:
Operator Description Example
== Equal to x == y
!= Not equal to x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal x >= y
to
<= Less than or equal to x <= y

3. Logical Operators
Used to combine boolean expressions:
Operato Description Example
r
and True if both conditions are true x > 5 and y < 10
or True if at least one condition is true x > 5 or y < 10
not Inverts boolean value not x

C. Type Conversion
Type conversion (type casting) is converting one data type into another.
1. Implicit Type Conversion (Done automatically by Python)
python
x = 10

8
y = 2.5
z = x + y # Converts 'x' to float automatically
print(type(z)) # Output: <class 'float'>

2. Explicit Type Conversion (Manually converting using functions)


python

# Converting int to float


a = float(10) # Output: 10.0

# Converting float to int


b = int(3.14) # Output: 3

# Converting string to int


c = int("123") # Output: 123

Conclusion

 Python offers various data types to store and manipulate data efficiently.
 Operators help perform mathematical, logical, and comparison operations.
 Expressions combine variables and operators to produce a result.
 Type conversion is crucial when handling different data types in operations

B. Operators
Operators are symbols used to perform operations on variables and values. Python supports
different types of operators categorized as follows:
 Arithmetic Operators
 Comparison (Relational) Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Membership Operators
 Identity Operators
Understanding operators is crucial for performing computations, comparisons, and logical
evaluations in Python programs.

9
1. Arithmetic Operators
Used for mathematical operations:
Operator Description Example (x = 10, y = 3) Output
+ Addition x + y 13
- Subtraction x - y 7
* Multiplication x * y 30
/ Division x / y 3.33
// Floor Division x // y 3
% Modulus (Remainder) x % y 1
** Exponentiation x ** y 1000

2. Comparison (Relational) Operators


Used to compare values and return True or False:
Operator Description Example (a = 5, b = 10) Output
== Equal to a == b False
!= Not equal to a != b True
> Greater than a > b False
< Less than a < b True
>= Greater than or equal to a >= b False
<= Less than or equal to a <= b True

3. Bitwise Operators
Operate at the binary level on numbers:
Operato Description Example (x = 2 (10), y = 7 (111)) Output
r
& AND x & y 2 (10)
` ` OR `x
^ XOR x ^ y 5 (101)
~ NOT ~x -3
<< Left Shift x << 1 4
>> Right Shift y >> 1 3

4. Logical Operators
Used for boolean logic:
Operator Description Example (x = 5, y = 10) Output
and Returns True if both conditions are True x > 0 and y > 5 True
or Returns True if at least one condition is True x > 10 or y > 5 True
not Reverses boolean value not (x > y) True

5. Assignment Operators
Used to assign values to variables:
Operato Example (x = 5) Equivalent To Result
r
= x = 5 x = 5 5
+= x += 3 x = x + 3 8
-= x -= 2 x = x - 2 6
*= x *= 4 x = x * 4 20

10
/= x /= 5 x = x / 5 4.0
//= x //= 3 x = x // 3 1
%= x %= 2 x = x % 2 1
**= x **= 2 x = x ** 2 25

6. Membership Operators
Used to check if a value exists in a sequence (list, string, set, dictionary).
Operato Description Example (x = [1, 2, 3]) Output
r
in Returns True if value exists 2 in x True
not in Returns True if value does not exist 5 not in x True

7. Identity Operators
Used to compare memory locations of objects.
Operator Description Example (a = 10, b = 10) Output
is Returns True if both refer to the same object a is b True
is not Returns True if they refer to different objects a is not b False

C. Expressions
An expression is a combination of values, variables, operators, and functions that evaluates to a
single value.
1. Arithmetic Expressions
Involves mathematical operations:

Example:

python
result = (2 + 3) * 5 # Output: 25

 Operator Precedence follows PEMDAS:


1. Parentheses: ()
2. Exponentiation: **
3. Multiplication/Division: *, /, //, %
4. Addition/Subtraction: +, -

2. String Expressions
Used for string concatenation and manipulation.

Example:

python

greeting = "Hello" + " " + "World!" # Output: "Hello World!"

3. Logical Expressions
Evaluate boolean conditions.

11
Example:

python
is_valid = (5 > 3) and (10 < 20) # Output: True

4. Function Call Expressions


Use functions within expressions.

Example:

python
def square(num):
return num ** 2

result = square(4) + 10 # Output: 26

5. Compound Expressions
Combine multiple expressions.

Example:

python

a, b = 5, 10
result = (a * 2) + (b / 2) # Output: 15.0

Conclusion

 Python operators allow for computations, comparisons, and logical operations.


 Expressions combine variables, values, and operators to produce results.
 Operator precedence determines the order in which operations are performed.
 Understanding and using different types of expressions helps in writing efficient Python
programs.

Student Notes on Python Programming Concepts

1.4 Sequence, Selection, and Iteration Constructs


In Python, sequence, selection, and iteration constructs control the flow of a program, enabling
developers to organize code, make decisions, and execute repetitive tasks efficiently.
A. Sequence

 Sequences are ordered collections of elements.


 Common sequence types in Python:
o Lists: Mutable and allow modifications.
o Tuples: Immutable and cannot be changed after creation.
o Strings: Sequences of characters.

12
B. Selection (Conditional Statements)
Selection constructs allow decision-making using if, elif, and else statements.

 Basic If Statement: Executes a block of code if a condition is True.


 If-Else Statement: Provides an alternative block if the condition is False.
 If-Elif-Else Statement: Checks multiple conditions sequentially.
 Nested If Statements: Enables complex decision-making with conditions inside conditions.

C. Iteration (Loops)
Loops enable repetition of a block of code.

 For Loop:
o Iterates over a sequence (list, tuple, range, etc.).
o Syntax: for variable in sequence:
o The range() function is commonly used to define numeric sequences.

 While Loop:
o Executes as long as a condition remains True.
o Syntax: while condition:

 Else in Loops:
o The else clause executes after the loop completes unless terminated by break.

 Jump Statements:
o break: Exits the loop prematurely.
o continue: Skips the current iteration and proceeds to the next.

1.5 Modular Programming Approach


Modular programming is a software design technique that breaks down complex systems into
smaller, independent modules.
A. Importing Modules
Modules are Python files (.py) containing functions and statements that can be reused in
programs.

 Importing a Module:
 import math
 Importing Specific Functions:
 from math import sin, pi
 Importing Multiple Modules:
 import math, random
 Importing All Names from a Module:
 from math import *

B. Designing and Writing Modules


Creating a module involves defining functions and saving them in a .py file.
Example:
# fibonacci.py

13
def fibonacci(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print()

This module can be imported and used in another Python program.

C. Importing Names from a Module Directly


Instead of importing the entire module, specific functions can be imported to be used directly.
from fibonacci import fibonacci
fibonacci(10)
By following modular programming principles, code becomes more readable, maintainable, and
reusable.
Arrays and Arrays of Objects in Python

1. Introduction to Arrays

In Python, arrays are fundamental data structures used to store collections of items. The key
distinction between arrays and lists in Python is that arrays store elements of the same data type,
while lists can store elements of different data types.

 Arrays: Typically use the array module and require a specific data type declaration such as
integers (i), floats (f), or characters (c).
 Lists: More flexible and can store mixed data types.
Arrays are more efficient in terms of memory usage and performance, as they store items of a
single type and are optimized for such use cases.
2. Array Syntax
 Elements: The items stored in the array.
 Index: The position where an element is stored in the array (starts at 0).
 Length: The total number of elements in the array.
 Indices: A map of indexes that indicate where each element is stored.
Example array:
csharp
[5, 6, 7, 2, 3, 5]
Index: 0 1 2 3 4 5

3. Python Built-in Array Module


The array module in Python is used to define arrays. Arrays contain objects with basic data
types like integers, floating-point numbers, or characters.
Syntax to create an array:
python
import array
arrayName = array.array('dataType', [array_items])
 arrayName: Variable name for the array.
 'dataType': Type code for the elements (e.g., 'i' for integer).
 [array_items]: A list or tuple containing the elements of the array.

14
Example:
python
import array
myarray = array.array('i', [1, 2, 3, 4])
print(myarray)

4. Basic Operations on Arrays


 Traversing an Array: Access elements using:

1. Indexing: Using the index of the element.


python
arr = array.array('i', [5, 6, 7, 2, 3, 5])
print(arr[2]) # Access element at index 2 (Output: 7)
2. Slicing: Using the slice operator [start:stop:stride].
python
print(arr[1:4]) # Access elements from index 1 to 3 (Output:
array('i', [6, 7, 2]))
3. Looping: Using for loops or enumerate() to iterate through array elements.
python
for element in arr:
print(element)
 Inserting into an Array:

o Arrays don't have a direct insert() method like lists.


o Convert the array to a list, perform the insertion, and then convert back to an array:
python
arr = array.array('i', [5, 6, 7, 2, 3])
arr_list = list(arr) # Convert array to list
arr_list.insert(2, 10) # Insert element 10 at index 2
arr = array.array('i', arr_list) # Convert back to array
print(arr) # Output: array('i', [5, 6, 10, 7, 2, 3])
Appending Elements:

o The append() method adds a single element at the end of the array.
python

arr = array.array('i', [1, 2, 3])


arr.append(4) # Appends 4 to the end of the array
print(arr) # Output: array('i', [1, 2, 3, 4])

5. Arrays of Objects
You can create arrays of custom objects using classes. Here's how to do that:
1. Define a Class to represent an object with attributes.
2. Create an Array of these objects using the array module.
Example:
python
import array

class Student:
def __init__(self, name, age):

15
self.name = name
self.age = age

# Create objects
student1 = Student('Alice', 20)
student2 = Student('Bob', 22)

# Create array of objects


students = array.array('O', [student1, student2]) # 'O' is for object type
print(students[0].name) # Output: Alice

6. Key Takeaways
 Arrays in Python are optimized for performance and memory when storing items of the same
data type.
 Use the array module for creating arrays and perform operations like traversing, inserting, and
appending.
 Arrays of custom objects can be created using Python's object-oriented features, where each
element of the array is an instance of a class.
1. Extending Elements in Arrays
In Python, the extend() method is used to append multiple elements from another array, list, or
iterable at the end of an array.
 extend() Method: Adds elements from an iterable (like a list or another array) to the end of
the array. This differs from append(), which adds only a single element.

2. Example of Using extend() with Arrays


Here’s how you can use the extend() method with arrays:
1. Creating Two Arrays: First, two arrays are created.
2. Extending the First Array: The extend() method is used to append elements from the second
array to the first array.
3. Updated Array: The result will show the first array with elements from the second array added
to the end.

Example:

python
import array

# Create two arrays of integers


int_array_1 = array.array('i', [1, 2, 3])
int_array_2 = array.array('i', [4, 5, 6])

# Use extend() to add elements of int_array_2 to int_array_1


int_array_1.extend(int_array_2)

# Print the updated int_array_1


print(int_array_1) # Output: array('i', [1, 2, 3, 4, 5, 6])

3. Key Points:

 extend() adds multiple elements (from an iterable) at the end of an array.


 The operation modifies the original array by adding the elements of the iterable.

16
 Difference with append(): While append() adds a single element to the array, extend()
adds all elements from an iterable to the array.

4. Use Cases:

 When you need to merge two arrays or lists into one.


 When you want to add elements from any iterable (like another array, list, or tuple) to the end
of your array.

17

You might also like