0% found this document useful (0 votes)
45 views9 pages

Basic Oops

basics oops

Uploaded by

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

Basic Oops

basics oops

Uploaded by

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

Python Classes/Objects

Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class
To create a class, use the keyword class:

ExampleGet your own Python Server

Create a class named MyClass, with a property named x:

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:

def __init__(self, name, age):

self.name = name

self.age = age

def greet(self):

print("Hello, my name is " + self.name+str(self.age) )

# Create a new instance of the Person class and assign it to the variable person1

person1 = Person("Ayan", 25)


person1.greet()

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.

Inheritance is a concept in object-oriented programming where a new class (child or derived


class) can inherit attributes and methods from an existing class (parent or base class). Here's an
example with a parent class Person and a child class Student that inherits from it:

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.")

# Create an instance of the Student class


student = Student(name="Anil", age=20, student_id="S12345")

# Call methods from the parent class


student.display_info()

# Call methods specific to the child class


student.study()
The syntax of multi-level inheritance is given below.

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

# Private attribute (denoted by a single underscore prefix)


self._year = year

# Public method
def display_info(self):
print(f"{self._year} {self.make} {self.model}")

# Getter method for the private attribute


def get_year(self):
return self._year

# Setter method for the private attribute


def set_year(self, year):
if year > 0:
self._year = year
else:
print("Invalid year. Please provide a positive value.")

# Create an instance of the Car class


my_car = Car(make="Toyota", model="Camry", year=2020)

# Access public attributes


print("Make:", my_car.make)
print("Model:", my_car.model)

# Access private attribute using a getter method


print("Year:", my_car.get_year())

# 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

# Use the setter method to update the year (recommended way)


my_car.set_year(2022)

# Display car information


my_car.display_info()

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

# Create an instance of the Calculator class


calculator = Calculator()
# Call the add method with different numbers of arguments
result1 = calculator.add(1)
result2 = calculator.add(1, 2)
result3 = calculator.add(1, 2, 3)

print("Result 1:", result1)


print("Result 2:", result2)
print("Result 3:", result3)

Method Overriding:

Method overriding occurs when a subclass provides a specific implementation for a


method that is already defined in its superclass. This allows objects of the subclass to be
used wherever objects of the superclass are expected.

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")

# Create instances of the subclasses


dog = Dog()
cat = Cat()

# Call the make_sound method on different objects


dog.make_sound() # Outputs: Woof
cat.make_sound() # Outputs: Meow
Abstraction
Abstraction is a concept in object-oriented programming that involves hiding the
implementation details and showing only the necessary features of an object. In Python,
abstraction can be achieved through the use of abstract classes and abstract methods.

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

# Define an abstract class with abstract methods


class Shape(ABC):
@abstractmethod
def area(self):
pass

@abstractmethod
def perimeter(self):
pass

# Create a concrete class that inherits from the abstract class


class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width

def area(self):
return self.length * self.width

def perimeter(self):
return 2 * (self.length + self.width)

# Create an instance of the concrete class


rectangle = Rectangle(length=5, width=3)

# Access methods defined in the abstract class


print("Area:", rectangle.area())
print("Perimeter:", rectangle.perimeter())

• 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.

You might also like