Object Oriented Programming Summary
Understand problem-solving aspects and features of Python.
Acquire knowledge of various data types and decision control statements, such as integers, floats, strings, lists, tuples, and dictionaries, as well as conditional statements like if, elif, and else.
Design solutions using functions and strings, ensuring clarity and reusability in code structure.
Learn file handling techniques including reading and writing to text files, using the open() function, and implementing data storage with dictionaries for easy retrieval.
Explore features of object-oriented programming (OOP), emphasizing the creation and manipulation of classes and objects for effective programming.
Features of Object-Oriented Programming (OOP)
Classes: Blueprints for creating objects that encapsulate data and functionality.
Objects: Instances of classes that interact through methods, allowing for robust software design.
Methods and message passing: Functions defined in classes that operate on the class's data. For instance, a method in a
Carclass might calculate fuel efficiency based on the distance driven and fuel consumed.Inheritance: The mechanism for creating new classes based on existing ones. For example, a
Vehicleclass could be the base forCar,Bike, andTruckclasses, each inheriting common features while adding unique attributes.Polymorphism: The ability for different classes to be treated as instances of the same class through shared methods. For example, a
draw()method could be used for differentShapeclasses, likeCircleandSquare, which have their specific implementation of the method.Containership: Represents a relationship where one class (the container) holds objects of another. For example, a
Libraryclass containing a list ofBookobjects.Reusability: Facilitating the use of existing code for new purposes, enhancing efficiency in development.
Delegation: A design pattern enabling one object to control the behavior of another, achieving better separation of concerns.
Data abstraction and encapsulation: Wrapping methods and properties to restrict access to the internal state, promoting modularity.
Key Concepts of OOP in Python
Class
A basic entity in OOP declared with the
classkeyword.Consists of attributes (data members) and methods (functions).
Example:
class Dog:
def __init__(self, name, breed):
self.name = name # Instance variable
self.breed = breed # Instance variable
def bark(self):
return "Woof!"
Object
An instance of a class (e.g.,
my_dog = Dog('Buddy', 'Golden Retriever')).Objects are interactive and communicate via messages.
Example:
print(my_dog.bark()) # Output: Woof!
Inheritance
Mechanism to create new classes from existing ones (base and derived classes).
Example: A
Shapeclass can lead toCircle,Line, andRectanglederived classes with specific attributes and methods relevant to each shape.
class Shape:
def area(self):
pass # To be implemented in derived classes
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * (self.radius ** 2)
Polymorphism
Ability to perform the same operation in various forms.
Example: A
cleanmethod can apply to different objects likeDishes,Cars, etc.
class Dishes:
def clean(self):
return "Dishes are cleaned."
class Car:
def clean(self):
return "Car is washed."
Encapsulation
Binding the data with the methods in a class to restrict access to certain details.
Provides access levels: Public and Private.
Example:
class Account:
def __init__(self, balance):
self.__balance = balance # Private attribute
def get_balance(self):
return self.__balance
Abstraction
Hiding unnecessary details to show only essential features.
Example: In a banking system, users interact with a simplified interface for transactions without needing to know the complex underlying logic.
Containership
One class contains objects of another class, enabling composition.
Example:
class Library:
def __init__(self):
self.books = [] # Contains multiple Book objects
def add_book(self, book):
self.books.append(book)
Delegation
One class depends on another but does not require it to exist for itself.
Example: A Car class that uses an Engine class object but functions independently.
Class Attributes vs Instance Attributes
Class Variables: Shared across all instances.
Instance Variables: Unique to each instance.
Methods
Constructor (init)
Initializes an object when it is created.
Example:
def __init__(self, name, marks):
self.name = name
self.marks = marks
Destructor (del)
Cleans up before an object is deleted.
Commonly Used Functions in OOP
hasattr(object, attribute): Checks if an attribute exists.getattr(object, attribute, default): Gets the attribute's value.setattr(object, attribute, value): Sets the attribute's value.delattr(object, attribute): Deletes the specified attribute.
Memory Management
Garbage Collection
Automatic memory management to free unwanted objects.
Techniques include: Reference counting and generational garbage collection.
Summary of Key Terms
Public Members: Accessible outside the class.
Private Members: Accessible only within the class using a double underscore prefix.
Static Methods: Defined using
@staticmethod, do not access class instance data.Class Methods: Defined using
@classmethod, take cls as first parameter.
Practical Applications
Create classes for defining entities (e.g.,
Car,Book,Employee) that encapsulate data and functions pertinent to their real-world counterparts.Implement methods to interact with objects and perform operations (e.g., displaying information, calculating values, managing records in a library system).
Class
A blueprint or template for creating objects.
Defines the attributes (data) and methods (behavior) that the objects of that class will have.
Declared using the
classkeyword.Example:
class Dog:
def __init__(self, name, breed):
self.name = name # Instance variable
self.breed = breed # Instance variable
def bark(self):
return "Woof!"
Object
An instance of a class.
It is a real-world entity that has state (data) and behavior (methods).
Objects are created from classes.
Objects interact with each other through methods.
Example:
my_dog = Dog('Buddy', 'Golden Retriever') # Creating an object
print(my_dog.bark()) # Output: Woof!
Feature | Class | Object |
|---|---|---|
Definition | Blueprint or template | Instance of a class |
Creation | Defined using the | Created from a class |
Memory | No separate memory is allocated | Memory is allocated when an object is created |
Purpose | Defines attributes and behaviors | Represents a specific entity with its own state and behavior |
Example |
|
|
Class
A blueprint or template for creating objects.
Defines the attributes (data) and methods (behavior) that the objects of that class will have.
Declared using the
classkeyword.Example:
class Dog:
def __init__(self, name, breed):
self.name = name # Instance variable
self.breed = breed # Instance variable
def bark(self):
return "Woof!"
Object
An instance of a class.
It is a real-world entity that has state (data) and behavior (methods).
Objects are created from classes.
Objects interact with each other through methods.
Example:
my_dog = Dog('Buddy', 'Golden Retriever') # Creating an object
print(my_dog.bark()) # Output: Woof!
Feature | Class | Object |
|---|---|---|
Definition | Blueprint or template | Instance of a class |
Creation | Defined using the | Created from a class |
Memory | No separate memory is allocated | Memory is allocated when an object is created |
Purpose | Defines attributes and behaviors | Represents a specific entity with its own state and behavior |
Example |
|
|
Data abstraction and encapsulation are fundamental to OOP because they manage complexity, ensure data integrity, and promote modularity.
Data Abstraction:
Focuses on essential features, hiding complex details.
Reduces complexity by simplifying object interaction.
Involves designing clear interfaces for object interaction.
Example: Driving a car requires knowing only the basic controls.
Encapsulation:
Protects data by bundling it with methods and restricting direct access.
Hides implementation