0% found this document useful (0 votes)
3 views8 pages

Introduction To OOP Lesson008

The document provides an introduction to object-oriented programming (OOP) in Python, explaining key concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It also covers constructors and destructors, detailing their roles in object initialization and cleanup, as well as access specifiers (public, private, protected) that control access to class members. Examples illustrate these concepts, demonstrating how they contribute to modularity, reusability, maintainability, and scalability in programming.

Uploaded by

BRIAN MUTURI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

Introduction To OOP Lesson008

The document provides an introduction to object-oriented programming (OOP) in Python, explaining key concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It also covers constructors and destructors, detailing their roles in object initialization and cleanup, as well as access specifiers (public, private, protected) that control access to class members. Examples illustrate these concepts, demonstrating how they contribute to modularity, reusability, maintainability, and scalability in programming.

Uploaded by

BRIAN MUTURI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

introduction to object-oriented programming in python

Object-oriented programming (OOP) is a programming paradigm centered around


the concept of "objects," which encapsulate data (attributes) and the code that
operates on that data (methods). In Python, OOP is facilitated through classes,
which serve as blueprints for creating objects.
Key Concepts of OOP in Python
 Class:
A class is a blueprint or template for creating objects. It defines the attributes and
methods that the objects of that class will possess.
 Object:
An object is an instance of a class. It is a concrete entity that has its own state
(values of attributes) and behavior (implementation of methods).
 Encapsulation:
Encapsulation is the bundling of data and methods that operate on that data within
a class. It restricts direct access to some of the object's components, preventing
accidental modification of data.
 Inheritance:
Inheritance allows a class (subclass or child class) to inherit attributes and methods
from another class (superclass or parent class). This promotes code reusability and
establishes a hierarchical relationship between classes.
 Polymorphism:
Polymorphism enables objects of different classes to be treated as objects of a
common type. It allows methods to be implemented differently in different classes,
providing flexibility and adaptability.
 Abstraction:
Abstraction involves simplifying complex systems by modeling classes based on
essential properties and behaviors, hiding unnecessary implementation details.
Example
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed

def bark(self):
print("Woof!")

my_dog = Dog("Buddy", "Golden Retriever")


print(my_dog.name)
my_dog.bark()
In this example, Dog is a class, and my_dog is an object of the Dog class. The
class has attributes name and breed, and a method bark().
Benefits of OOP
Modularity: OOP promotes modularity by organizing code into self-contained
objects.
Reusability: Inheritance allows for the reuse of code, reducing redundancy and
development time.
Maintainability: Encapsulation and abstraction make code easier to understand,
modify, and maintain.
Scalability: OOP facilitates the development of large and complex systems by
breaking them down into manageable objects.
constructors and destructors in oop in python
Constructors and destructors are special methods in Python classes used for object
initialization and cleanup, respectively.
Constructors
A constructor is automatically called when an object is created. In Python, it's
defined using the __init__ method. It initializes the object's attributes.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
print(f"{self.name} is a {self.breed}")

my_dog = Dog("Buddy", "Golden Retriever")


# Output: Buddy is a Golden Retriever

Destructors
A destructor is automatically called when an object is about to be destroyed. It's
defined using the __del__ method. It's often used for cleanup tasks, like releasing
resources. However, Python's garbage collection usually handles memory
management, reducing the need for explicit destructors.
class Dog:
def __init__(self, name):
self.name = name
print(f"{self.name} created")

def __del__(self):
print(f"{self.name} destroyed")

my_dog = Dog("Buddy")
del my_dog
# Output:
# Buddy created
# Buddy destroyed

Usage
Constructors are essential for setting up objects, while destructors are less
commonly used in Python due to automatic garbage collection. Destructors are
useful in situations where external resources need to be released explicitly.

Access specifiers in python (public, private, protected)


Access modifiers are used by object-oriented programming languages like C+
+,java, python etc. to restrict the access of the class member variable and methods
from outside the class. Encapsulation is an OOPs principle which protects the
internal data of the class using Access modifiers like Public, Private and Protected.
Python supports three types of access modifiers which are public, private and
protected. These access modifiers provide restrictions on the access of member
variables and methods of the class from any object outside the class.

Public Access Modifier


By default the member variables and methods are public which means they can be
accessed from anywhere outside or inside the class. No public keyword is required
to make the class or methods and properties public. Here is an example of Public
access modifier
Example
The student class has two member variables, name and age and a method display
which prints the member variable values. Both these variables and the methods are
public as no specific keyword is assigned to them.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age

def display(self):
print("Name:", self.name)
print("Age:", self.age)

s = Student("John", 20)
s.display()
Output
Name: John
Age: 20

Private Access Modifier


Class properties and methods with private access modifier can only be accessed
within the class where they are defined and cannot be accessed outside the class. In
Python private properties and methods are declared by adding a prefix with two
underscores(?__') before their declaration.
Example
The Class BankAccount is being declared with two private variables i.e
account_number and balance and a private property display_balance which prints
the balance of the bank account. As both the properties and method are private so
while accessing them from outside the class it raises Attribute error.
class BankAccount:
def __init__(self, account_number, balance):
self.__account_number = account_number
self.__balance = balance

def __display_balance(self):
print("Balance:", self.__balance)

b = BankAccount(1234567890, 5000)
b.__display_balance() # Trying to access private method
output
AttributeError: 'BankAccount' object has no attribute '__display_balance'
Why Does This Error Happen
Because of Python’s name mangling for private members.
When you define a method or variable with two leading underscores like
__display_balance, Python internally renames it to make it harder to access from
outside the class.
__display_balance --> _BankAccount__display_balance
This is done to:
 Prevent accidental access or modification of private members.
 Avoid name conflicts in subclasses.

Protected Access Modifier


Class properties and methods with protected access modifier can be accessed
within the class and from the class that inherits the protected class. In python,
protected members and methods are declared using single underscore(?_') as prefix
before their names.
Example
The Person class has two protected properties i.e _name and _age and a protected
method _display that displays the values of the properties of the person class. The
student class is inherited from Person class with an additional property i.e
_roll_number which is also protected and a public method display that class the
_display method of the parent class i.e Person class by creating an instance of the
Student class we can call the display method from outside the class as the display
method is private which calls the protected _display method of Person class.
class Person:
def __init__(self, name, age):
self._name = name
self._age = age

def _display(self):
print("Name:", self._name)
print("Age:", self._age)

class Student(Person):
def __init__(self, name, age, roll_number):
super().__init__(name, age)
self._roll_number = roll_number

def display(self):
self._display()
print("Roll Number:", self._roll_number)
s = Student("John", 20, 123)
s.display()

output
Name: John
Age: 20
Roll Number: 123

Type Syntax Access level

Public def method() Accessible everywhere

Protected (by convention) _method() Shouldn't be accessed outside class/subclass

Private (enforced by name mangling) __method() Can't be accessed directly

You might also like