Docsity

Object Oriented Programing, Schemes and Mind Maps of Object Oriented Programming

Toggle sidebar
bg1
MIDTERM NA SIS ANONEY
Module 5: Object-Oriented Programming
Organize larger applications with structured,
reusable code. OOP lets you define your own
objects with custom attributes and behaviors -
built around four core principles: Encapsulation,
Abstraction, Polymorphism, and Inheritance.
Everything Is a Class
Python follows the "first-class everything"
principle functions. OOP becomes essential as
applications grow, every value is an instance of
a class, including integers, lists, and letting you
define custom blueprints for structured,
repeatable code.
• Encapsulation
Bundle data and behavior together
• Abstraction
Hide complexity, expose essentials
• Polymorphism
One interface, many forms
• Inheritance
Reuse and extend existing classes
Key OOP Terminology
Master these five terms - they form the
vocabulary of every OOP conversation in
Python.
Term
Definition
Class
A blueprint defining attributes
and methods for objects
Object/Instance
A unique creation built from a
class blueprint Instantiation
Instantiation
The process of creating an
instance from a class
Attribute
A variable holding data
associated with an object
Method
A function defined inside a
class that operates on its
objects
A class is a blueprint. An object is the real thing
built from it. The_init_() method runs
automatically to set up each new object's initial
state
• class keyword: Defines the blueprint (e.g.,
Parrot)
• Object: A specific instance (e.g., blu =
Parrot())
• Attributes: Characteristics like name, age
• Methods: Behaviors like sing() or-fly()
• init (): Auto-runs on creation to assign initial
values
TWO TYPES OF ATTRIBUTES
Attributes store data on objects. Python
distinguishes between data unique to each
instance and data shared across all instances of
a class.
• Instance Attribute
Unique to each object. Defined using
self.attribute_name.
Example: Each dog has its own name "Rex",
"Bella", etc.
• Class Attribute
Shared identically across all instances. Defined
directly in the class.
Example: Every dog shares species = "mammal'
PRINCIPLES
Inheritance: Build on What Exists
Inheritance lets you create new classes based
on existing ones promoting code reuse and
reducing complexity. The derived class
automatically gains all attributes and methods of
its parent.
class Prod:
def total_price(self):
qty = int(input("Enter
quantity: "))
total = qty * self.price
print("total price: ",
total)
class book(Prod):
price = 100
bk = book()
bk.total_price()
Polymorphism: One Name, Many Forms
Different classes can share the same method
name. Python executes the correct behavior
based on the object passed enabling universal
functions that work across multiple types.
class Prod:
def total_price(self):
print("Calculating total
price")
class book(Prod):
def total_price(self):
qty = int(input("Enter
Quantity: "))
total = qty * 100
print("Total Quantity:
", total)
bk = book()
bk.total_price()
Special Methods: Python's Magic
Dunder methods (double underscore) are
triggered automatically by Python syntax - you
rarely call them directly. They give your objects
built-in behavior.
1. _init_()
Initializes a new object on creation
2. _str_()
Controls how print() displays the object
pf3
pf4
pf5

Partial preview of the text

Download Object Oriented Programing and more Schemes and Mind Maps Object Oriented Programming in PDF only on Docsity!

MIDTERM NA SIS ANONEY

Module 5: Object-Oriented Programming Organize larger applications with structured, reusable code. OOP lets you define your own objects with custom attributes and behaviors - built around four core principles: Encapsulation, Abstraction, Polymorphism, and Inheritance. Everything Is a Class Python follows the " first-class everything " principle functions. OOP becomes essential as applications grow, every value is an instance of a class, including integers, lists, and letting you define custom blueprints for structured, repeatable code.

  • Encapsulation Bundle data and behavior together - Abstraction Hide complexity, expose essentials - Polymorphism One interface, many forms - Inheritance Reuse and extend existing classes Key OOP Terminology Master these five terms - they form the vocabulary of every OOP conversation in Python. Term Definition Class A blueprint defining attributes and methods for objects Object/Instance A unique creation built from a class blueprint Instantiation Instantiation The process of creating an instance from a class Attribute A variable holding data associated with an object Method A function defined inside a class that operates on its objects A class is a blueprint. An object is the real thing built from it. The init() method runs automatically to set up each new object's initial state
  • class keyword: Defines the blueprint (e.g., Parrot)
  • Object: A specific instance (e.g., blu = Parrot())
  • Attributes: Characteristics like name, age
  • Methods: Behaviors like sing() or-fly()
  • init (): Auto-runs on creation to assign initial values TWO TYPES OF ATTRIBUTES Attributes store data on objects. Python distinguishes between data unique to each instance and data shared across all instances of a class. - Instance Attribute Unique to each object. Defined using self.attribute_name. Example: Each dog has its own name "Rex", "Bella", etc. - Class Attribute Shared identically across all instances. Defined directly in the class. Example: Every dog shares species = "mammal' PRINCIPLES Inheritance: Build on What Exists Inheritance lets you create new classes based on existing ones promoting code reuse and reducing complexity. The derived class automatically gains all attributes and methods of its parent.

class Prod:

def total_price(self):

qty = int(input("Enter

quantity: "))

total = qty * self.price

print("total price: ",

total)

class book(Prod):

price = 100

bk = book()

bk.total_price()

Polymorphism: One Name, Many Forms Different classes can share the same method name. Python executes the correct behavior based on the object passed enabling universal functions that work across multiple types.

class Prod:

def total_price(self):

print("Calculating total

price")

class book(Prod):

def total_price(self):

qty = int(input("Enter

Quantity: "))

total = qty * 100

print("Total Quantity:

", total)

bk = book()

bk.total_price()

Special Methods: Python's Magic Dunder methods (double underscore) are triggered automatically by Python syntax - you rarely call them directly. They give your objects built-in behavior.

1. init() Initializes a new object on creation 2. str() Controls how print() displays the object

3. len() Enables 1en() on your custom objects 4. del() Runs when an object is deleted from memory OOP in Action: The Full Picture These four principles work together to make Python code organized, scalable, and maintainable. - Encapsulation Bundle data and methods inside a class, controlling access and protecting state. - Abstraction Hide complex internals; expose only what users need to interact with.

  • Polymorphism Use a single interface for multiple object types with shared method names. - Inheritance Derive new classes from existing ones, reusing and extending their behavior. Module 6: Modular Programming and Error Handling Lesson 1: Python Modules and Packages This lesson focuses on how to break a large programming task into separate, manageable subtasks. A module is simply a Python file (py extension) containing functions, classes, or variables. Core Advantages of Modular Code Advantage Description Simplicity Focuses on a small portion of the problem, making development easier and less error-prone. Maintainability Minimizes interdependency, allowing updates to one module without breaking the whole application. Reusability Code written once can be easily imported and reused elsewhere, eliminating duplication. Scoping Creates separate namespaces to prevent variable or function name collisions across the program. Working with Modules To use a module's functionality in another file, you must load it into your namespace. Python offers several ways to do this: import module_name Imports the entire module. You access its functions using the prefix (e.g., module_name.function() ).

# import module_name

import datetime as dt

from math import

from math import sqrt

import math

number 16

result = math.sqrt(number)

print("The square root of",

number, "is", result)

**from module_name import *** Imports everything from the module. (Use cautiously, as it consumes more memory).

# from module_name import *

number 25

result = sqrt(number)

print("The square root of",

number, "is", result)

from module name import function name Imports only specific attributes, saving memory and removing the need for a prefix.

# from module name import

function name

# Importing everything from

Python's built-in 'math' module

# Now you can use any function

or constant from 'math'

directly,

# without prefixing it with

'math."

print(pi)

print(sqrt(16))

print(floor(4.7))

occurred

print(f"Success! (numerator) /

(denominator) = (result)")

break # Exit the loop on

valid input

finally:

# Always runs at the end of

each iteration

print("--- Attempt complete

Important Handling Techniques Catching Specific Exceptions It is best practice to specify the error you are looking for (e.g., except ValueError : or except ZeroDivisionError :). This allows you to handle different types of errors in distinct ways rather than using a blanket catch-all. Raising Exceptions You can manually trigger an exception in your code using the raise keyword (e.g., raise ValueError("Invalid number")). This is useful for enforcing your own constraints on user input. Catching Multiple Exceptions You can handle multiple specific errors in one line using a tuple : except (TypeError, ZeroDivisionError):. Using finally for Cleanup The finally block is essential when dealing with external resources like network connections, databases, or file operations. It guarantees that the resource is safely closed or disconnected, even if the program encountered a fatal error beforehand. MODULE 7: Decorators & Generators Two Features, One Goal: Better Python Both decorators and generators solve real problems - but in fundamentally different ways. Python Decorators Purpose : Extend or modify a function's behavior Syntax : The [@] symbol, functions as objects Benefit : Cleaner, modular, and "Pythonic" code Python Generators Purpose : Produce a sequence of values over time Syntax : The yield keyword, state suspension Benefit : Massive memory savings for large datasets LESSON 1: Python Decorators Decorators are functions that wrap around another function to change its behavior - without modifying the original code. To understand them, you first need to understand how Python treats functions. Functions Are First-Class Objects In Python, functions are just like integers, strings, or lists they can be assigned, passed around, and manipulated freely. Assign to Variables A function can be stored in a variable and called through it later. Pass as Arguments Functions can be passed into other functions to be executed inside. Return from Functions A function can return another function object omit () to pass the object itself, not execute it.

# Define a decorator that takes

a function as an argument

def my_decorator(func):

# Define a wrapper function

to add extra behavior

def wrapper():

# Print a message before

the original function runs

print("Before the function

runs")

# Call the original

function

func()

# Print a message after the

original function runs

print("After the function

runs")

# Return the wrapper

function

return wrapper

# Apply the decorator to the

say hello function on

# This is equivalent to:

say_hello

my_decorator(say_hello)

@my_decorator

def say_hello():

# Print a greeting message

print("Hello!")

# Call the decorated function

say_hello()

Nested Functions & Scope Functions Within Functions You can define an inner function inside another function. Due to Python's scope rules, the inner function is invisible to the rest of the program -it exists only within its parent. Variable Scope Each function creates its own local namespace. Variables defined inside are separate from global variables, preventing naming collisions and unintended side effects. Returning an inner function without parentheses () passes the object-not the result of calling it. The @ Decorator Syntax Manually wrapping functions is tedious. Python automates this with the @symbol placed directly above a function definition. </> Define wrapper @ Apply @decorator

▶ Run wrapped fn

LESSON 2: Iterators & Generators Generators produce sequence data on the fly rather than calculating an entire list upfront. This is critical for performance when working with massive datasets or infinite sequences. Yield & State Suspension The yield Statement Generators replace return with yield. When hit, the function returns a value and completely suspends its state - remembering exactly where it left off for the next call. One Value at a Time Because the generator pauses while awaiting the next instruction, it only ever holds one value in memory at a time - no matter how large the sequence. Regular Function

  • calculates all 100,000 values at once
  • stores full list in memory Generator Function
  • calculates only the next value when requested
  • suspends state with yield Controlling Generators: next() & iter() next() Asks a generator for its next yielded value. When exhausted, it raises StopIteration which for loops catch automatically. iter() Converts an iterable (like a list or string) into a strict iterator, unlocking the ability to call next() on it directly. for Loops Standard for loops work seamlessly with generators - they handle StopIteration behind the scenes, making generator code clean and readable.

# next()

# Define a generator function

def count_numbers():

yield 1

yield 2

yield 3

numbers = count_numbers()

#Get and print each value from

the generator

print(next(numbers)) # Output:

print(next(numbers)) # Output:

print(next(numbers)) # Output:

# iter()

print(iter(numbers)) # Output: