Programming 2 OOP

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

PROGRAMMING 2

Object-Oriented Programming
Object-Oriented Programming (OOP) is a paradigm for software development that organizes code into objects, which
are instances of classes, allowing for the creation of modular and reusable code. OOP fundamentally revolves
around the concept of objects, which represent real-world entities or concepts in a software system. These objects
encapsulate data and behavior, providing a way to model complex systems in a more manageable and intuitive
manner.

At the core of OOP are four key principles: encapsulation, inheritance, polymorphism, and abstraction. These
principles form the foundation upon which object-oriented systems are built, enabling developers to create robust,
flexible, and maintainable code.

Encapsulation is the practice of bundling data and methods that operate on that data within a single unit, called an
object. By encapsulating data, OOP hides the internal state of an object from external access, allowing for better
control over how data is manipulated and preventing unintended modifications. This enhances security and reduces
the risk of unintended side effects.

Inheritance is a mechanism that allows one class to inherit properties and behavior from another class. This
promotes code reuse and facilitates the creation of hierarchical relationships between classes. Through inheritance,
subclasses can extend and specialize the functionality of their parent classes, inheriting common attributes and
methods while adding new ones or overriding existing ones as needed.

Polymorphism enables objects of different classes to be treated as objects of a common superclass, allowing for
more flexible and modular code. Polymorphism allows methods to behave differently depending on the type of object
they are operating on, enabling dynamic dispatch and runtime flexibility. This enables developers to write code that is
more generic and adaptable to varying requirements.

Abstraction is the process of modeling complex systems by focusing on the essential aspects while hiding
unnecessary details. Abstraction allows developers to create simplified representations of real-world entities, making
it easier to understand and manage complex systems. By defining clear interfaces and hiding implementation details,
abstraction promotes modularity and code reuse while reducing complexity and coupling.

Together, these principles form the building blocks of object-oriented systems, enabling developers to create
software that is modular, extensible, and easy to maintain. OOP encourages a more intuitive and natural way of
thinking about software design by modeling systems in terms of objects and their interactions. This promotes better
organization, improves code readability, and facilitates collaboration among developers.

In addition to these principles, OOP also emphasizes concepts such as classes, objects, methods, properties, and
messages. Classes serve as blueprints for creating objects, defining their structure and behavior. Objects are
instances of classes, representing specific instances or occurrences of a concept. Methods are functions associated
with objects, defining their behavior and providing a way to interact with them. Properties are attributes of objects,
representing their state or characteristics. Messages are used to communicate between objects, enabling them to
interact and collaborate within a system.

Overall, Object-Oriented Programming provides a powerful and flexible approach to software development, enabling
developers to create systems that are modular, extensible, and easy to maintain. By organizing code into objects and
applying key principles such as encapsulation, inheritance, polymorphism, and abstraction, OOP promotes better
design, improved code quality, and increased productivity.
A Vague Overview of Different Programming Approaches

Aspect Procedural Programming Functional Programming Object-Oriented Programming


Linear, based on Declarative, based on Object-based, revolves around objects
Paradigm
procedure/function execution function evaluation and classes
May become complex with Encourages modular, understandable
Readability Often concise and expressive
larger programs code structure
Limited reusability due to tight Functions are often highly Promotes reusability through
Reusability
coupling reusable inheritance and polymorphism
State Emphasis on global data and Avoids mutable state, favors Uses encapsulation and instance
Management shared state immutability variables for state management
Limited support for Supports encapsulation Strong support for encapsulation
Encapsulation
encapsulation through closures through classes and access modifiers
Not inherent, typically Supports composition over Supports inheritance hierarchies for
Inheritance
achieved through code reuse inheritance code reuse
Functions can be
Achieved through function Built-in support for polymorphism
Polymorphism polymorphic via higher-order
overloading and overriding through inheritance and interfaces
functions
Can be challenging due to Debugging is simplified due Debugging is facilitated by clear class
Debugging
global state and side effects to immutability structures and methods
Can offer performance May introduce overhead due to
Can be efficient for small-
Performance benefits through lazy dynamic dispatch and inheritance
scale systems
evaluation lookup
Examples C, Pascal, Fortran Haskell, Scala, Clojure Java, Python, C++
The Advantages and Disadvantages of Object-Oriented Programming (OOP) in Python
Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of "objects,"
which can contain data, in the form of fields or attributes, and code, in the form of procedures or methods. Python, a
widely used high-level programming language, fully supports OOP principles. In this essay, we will explore the
advantages and disadvantages of using OOP in Python.

Advantages of OOP in Python:


1. Modularity:
 Encapsulation: OOP allows for bundling data and methods that operate on the data into single units, known
as objects. This promotes encapsulation, where the internal workings of an object are hidden from the
outside world, allowing for more manageable and modular code.
 Abstraction: OOP encourages abstracting away complex implementations and focusing on interfaces. This
allows developers to work at higher levels of abstraction, making code easier to understand, maintain, and
extend.
2. Reusability:
 Inheritance: Python supports inheritance, allowing classes to inherit attributes and methods from other
classes. This promotes code reuse by enabling the creation of new classes based on existing ones.
Developers can leverage existing code without having to reimplement functionality, leading to more efficient
development and fewer errors.
 Composition: In addition to inheritance, Python supports composition, where classes can contain instances
of other classes as attributes. This provides another mechanism for code reuse, allowing for greater
flexibility and modularity in design.
3. Extensibility:
 Polymorphism: Python supports polymorphism, which allows objects of different classes to be treated as
objects of a common superclass. This facilitates writing code that can work with objects of various types,
promoting flexibility and extensibility. Polymorphism allows for the implementation of generic algorithms that
can operate on objects of different classes, making code more adaptable to changing requirements.
 Dynamic Typing: Python's dynamic typing system enables objects to change types at runtime, providing
additional flexibility and extensibility. This allows developers to write code that can handle a wide range of
inputs without explicit type declarations, making Python well-suited for rapid prototyping and iterative
development.
4. Scalability:
 Class-based Structure: OOP promotes a structured approach to programming, where code is organized into
classes and objects. This makes it easier to manage large codebases by breaking them down into smaller,
more manageable components. With proper design and encapsulation, OOP in Python can scale effectively
to accommodate growing project requirements.
 Namespace Management: Python's support for namespaces and modules allows for effective management
of code dependencies and interactions. This promotes scalability by facilitating the creation of modular,
reusable components that can be easily integrated into larger systems.
5. Maintainability:
 Code Organization: OOP encourages organizing code into logical units (classes and objects), making it
easier to understand and maintain. By encapsulating related data and functionality within objects,
developers can isolate changes and minimize the impact of modifications on other parts of the codebase.
 Readability: Python's syntax and emphasis on simplicity and readability contribute to the maintainability of
OOP code. Clear, expressive code is easier to understand, debug, and modify, reducing the time and effort
required for maintenance tasks.
Disadvantages of OOP in Python:
1. Complexity:
 Learning Curve: OOP concepts such as inheritance, polymorphism, and encapsulation can be challenging
for beginners to grasp. Understanding how these concepts interact and when to apply them effectively
requires a certain level of experience and expertise.
 Overhead: OOP can introduce overhead in terms of memory and performance. Creating objects and
managing their interactions incurs additional computational costs compared to procedural programming.
While this overhead is often negligible in small-scale applications, it can become significant in performance-
critical systems or resource-constrained environments.
2. Verbosity:
 Boilerplate Code: OOP in Python can lead to verbose code, especially when defining classes and methods.
While Python's syntax is concise compared to languages like Java or C++, OOP principles such as
encapsulation and inheritance may require additional boilerplate code, leading to increased verbosity and
reduced clarity.
 Complexity: As object hierarchies grow more complex, maintaining and navigating the codebase can
become increasingly challenging. Deep class hierarchies with multiple levels of inheritance can obscure the
relationships between classes and make it harder to understand the overall system architecture.
3. Performance Overhead:
 Interpreted Language: Python is an interpreted language, which means that code execution tends to be
slower compared to compiled languages like C or C++. While Python's performance has improved
significantly over the years, it still lags behind compiled languages in terms of raw computational speed.
 Dynamic Typing: Python's dynamic typing system incurs runtime overhead due to type inference and
dynamic dispatch. While dynamic typing provides flexibility and expressiveness, it can lead to slower
execution speeds compared to statically typed languages.
4. Limited Control Over Memory Management:
 Garbage Collection: Python employs automatic memory management through garbage collection, which
can lead to unpredictable memory usage patterns and performance fluctuations. While garbage collection
simplifies memory management for developers, it can introduce overhead and occasional pauses during
execution, especially in memory-intensive applications.
 Resource Consumption: OOP in Python may lead to higher memory consumption compared to procedural
programming, as objects and their associated data structures incur additional memory overhead. While this
may not be a significant issue for small-scale applications, it can become a concern in memory-constrained
environments or when dealing with large datasets.
5. Design Complexity:
 Object Hierarchies: Designing effective object hierarchies requires careful consideration of relationships and
dependencies between classes. Poorly designed hierarchies can lead to tight coupling, where changes in
one part of the system have cascading effects on other parts. This can increase the complexity of the
codebase and make it harder to maintain and extend over time.
 Inheritance Pitfalls: While inheritance can promote code reuse, it can also lead to design pitfalls such as the
"diamond problem" and overly deep class hierarchies. Inappropriate use of inheritance can result in tightly
coupled classes and fragile base class problems, making the codebase harder to refactor and extend.

In conclusion, Object-Oriented Programming (OOP) in Python offers numerous advantages, including modularity,
reusability, extensibility, scalability, and maintainability. However, it also comes with certain disadvantages, such as
complexity, verbosity, performance overhead, limited control over memory management, and design complexity.
Understanding these trade-offs is essential for developers to make informed decisions about when and how to
leverage OOP principles in Python programming. Ultimately, the suitability of OOP depends on the specific
requirements and constraints of the project, as well as the preferences and expertise of the development team.
Classes in Python

In Python, classes serve as the blueprint for creating objects, allowing for the organization and structuring of code in
a modular and reusable manner. They facilitate the implementation of object-oriented programming (OOP) principles,
such as encapsulation, inheritance, and polymorphism. Understanding classes is fundamental to mastering Python's
OOP capabilities.

At its core, a class is a user-defined data type that bundles together data (attributes) and functions (methods) that
operate on that data. It provides a template for creating objects, which are instances of the class. Through classes,
you can model real-world entities or abstract concepts in your code, making it more intuitive and maintainable.

The syntax for defining a class in Python is straightforward:

Line 1 is considered as class definition. In this line, the class Student is being defined.
Line 2 to Line 6 is called the constructor or the __init__ method. Note that functions inside a class are typically called
methods. The constructor has four parameters (name, age, course, year). The self.name, self.age, self.course, and
self.year are called instance variables for storing data that are being passed into the four parameters of the
constructor.
Line 8 to Line 9 is the instance for the display_info method. This method prints out the student’s information.
Line 11 to Line 16 is the instance for the promote method. This method promotes the student to the next academic
year. Unless the student passed the 12th grade, in that case the string “{name} has already graduated!” will be
printed.
Line 18 to Line 20 is the instane for the shift method. This method allows the student to shift to a new course which is
the string that is passed as a parameter.
Line 22 creates an instance of the Student class and making it into an object called student1.
Line 24 invokes the display_info method on the student1 object, printing the student’s information.

Activity #1
Promote the student by invoking the promote() method as shown in Line 26.
This means that for the student to graduate, you will have to invoke the promote() method 13 times. Write a Python
loop (while or for loop) and reduce the number of lines of code to just three. Paste your code in the Google
Classroom Activity.

Activity #2

Invoking the shift() method will change the student’s course to the string that was passed as a parameter. Create 9
more student objects and set their course to ‘BSIT’. Write a 3-line Python code that loop through all 10 students and
using the shift() method, change their course to “ComEng”. Paste your code in the Google Classroom Activity.

*** END ***

You might also like