Basic Oops
Basic Oops
Create a Class
To create a class, use the keyword class:
The self-parameter
The self-parameter refers to the current instance of the class and accesses the class variables. We can
use anything instead of self, but it must be the first parameter of any function which belongs to the class.
# # This is the constructor method that is called when creating a new Person object
## It takes two parameters, name and age, and initializes them as attributes of the object
class Person:
self.name = name
self.age = age
def greet(self):
# Create a new instance of the Person class and assign it to the variable person1
Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class.
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Child class is the class that inherits from another class, also called derived class.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
class Student(Person):
def __init__(self, name, age, student_id):
# Call the constructor of the parent class
super().__init__(name, age)
self.student_id = student_id
def display_info(self):
# Override the display_info method of the parent class
print(f"Name: {self.name}, Age: {self.age}, Student ID:
{self.student_id}")
def study(self):
print(f"{self.name} is studying.")
Syntax
1. class class1:
2. <class-suite>
3. class class2(class1):
4. <class suite>
5. class class3(class2):
6. <class suite>
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class BabyDog(Dog):
def eat(self):
print("Eating bread...")
d = BabyDog()
d.bark()
d.speak()
d.eat()
What is Encapsulation
Encapsulation is one of the fundamental principles of object-oriented programming
(OOP). It involves bundling the data (attributes) and the methods (functions) that operate on the
data into a single unit called a class. This concept helps in hiding the internal implementation
details of a class and exposing only what is necessary. In Python, encapsulation is achieved
through the use of private and protected attributes.
Example:-
class Car:
def __init__(self, make, model, year):
# Public attributes
self.make = make
self.model = model
# Public method
def display_info(self):
print(f"{self._year} {self.make} {self.model}")
# Try to set the year directly (which is not recommended due to encapsulation)
# This will not affect the private attribute directly
# my_car._year = 2022 # Commented out to avoid the error
What is polymorphism?
Polymorphism refers to having multiple forms. Polymorphism is a programming term that refers
to the use of the same function name, but with different signatures, for multiple types.
Method Overloading:
Method overloading in Python involves defining multiple methods in a class with the
same name but different parameter lists. Python does not natively support method
overloading like some other languages, but it can be simulated using default parameter
values.
Here's an example:
class Calculator:
def add(self, x, y=None, z=None):
if y is not None and z is not None:
return x + y + z
elif y is not None:
return x + y
else:
return x
Method Overriding:
Here's an example:
class Animal:
def make_sound(self):
print("Some generic sound")
class Dog(Animal):
def make_sound(self):
print("Woof")
class Cat(Animal):
def make_sound(self):
print("Meow")
Here's an example using the ABC (Abstract Base Class) module, which provides the infrastructure
for defining abstract base classes:
python
from abc import ABC, abstractmethod
@abstractmethod
def perimeter(self):
pass
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
• The Shape class is an abstract class with two abstract methods, area and perimeter.
Abstract methods are defined using the @abstractmethod decorator.
• The Rectangle class is a concrete class that inherits from the abstract class Shape. It
provides implementations for the abstract methods area and perimeter.
• An instance of the Rectangle class is created, and its methods are called. The fact
that the Rectangle class is a subclass of the abstract class Shape ensures that it
provides implementations for all abstract methods, making it a complete and
usable class.
Abstraction allows you to define a common interface for a group of related classes while
hiding the details of their individual implementations. It helps in organizing and
managing code in a more modular and understandable way.