0% found this document useful (0 votes)
4 views

Python_Basics (2)

Python

Uploaded by

Ketan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python_Basics (2)

Python

Uploaded by

Ketan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

UNIT- 1

OOP Fundamental (In Python)

Class: A class is a blueprint or a template that defines the characteristics


and behavior of an object. It's a user-defined data type that defines the
properties and methods (functions) that an object can have. A class is
essentially a design pattern or a template that defines how an object should
be created and what properties and methods it should have.

Objects: An object, on the other hand, is an instance of a class. It's a


concrete entity that has its own set of attributes (data) and methods
(functions) that are defined by the class. An object has its own set of
values for its attributes and can be manipulated independently of other
objects.

To illustrate the difference:

 A class is like a car factory (defines the characteristics and features


of a car)
 An object is like a specific car that rolls out of the factory (has
its own set of attributes, like color, model, and year)

In Python, you define a class using the class keyword, and you create an
object by calling the class using the () operator.

Example:

class Car:
def __init__(self, color, model):
self.color = color
self.model = model

def honk(self):
print("Beep!")

my_car = Car("red", "Toyota") # my_car is an object


my_car.honk() # Output: Beep!

In this example, Car is the class, and my_car is an object (an instance of
the Car class.

Constructor:

In Python, a constructor is a special method used to initialize newly created


objects. It's called when an object is instantiated from a class, and it
allows the class to set the initial state of the object.

In Python, the constructor method is named __init__. Here's an example:

class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age

obj = MyClass("John", 30)


print(obj.name) # Output: John
print(obj.age) # Output: 30

In this example, the __init__ method takes two parameters, name and age,
which are used to set the initial state of the object. When the object is
created, the __init__ method is called automatically, and the object's
attributes are set to the passed values.

Some key points about constructors in Python:

- The constructor method is named __init__


- It's called when an object is instantiated from a class
- It allows the class to set the initial state of the object
- It's typically used to set instance variables (attributes) of the object
- It can take any number of parameters, including zero (in which case it's
called a "no-arg" constructor)

Abstract method

An abstract class is a class that cannot be instantiated on its own and


typically serves as a blueprint for other classes. Abstract classes can
include abstract methods, which are methods declared in the abstract class
but do not have an implementation in it. Subclasses of the abstract class
are expected to implement these abstract methods.

Abstract classes are defined using the abc (Abstract Base Classes) module.
You need to import the ABC class and the abstractmethod decorator from the
abc module to define an abstract class.

Here's an example:

from abc import ABC, abstractmethod

class AbstractClassExample(ABC):
@abstractmethod
def abstract_method(self):
pass

def concrete_method(self):
print("This is a concrete method")

In this example:

- AbstractClassExample is an abstract class because it inherits from ABC.


- abstract_method is an abstract method because it's decorated with
@abstractmethod. This means that any subclass of AbstractClassExample must
implement this method.
- concrete_method is a concrete method because it's implemented in the
abstract class. Subclasses can use this method without implementing it.

To use an abstract class, you need to inherit from it and implement all the
abstract methods:

class ConcreteClassExample(AbstractClassExample):
def abstract_method(self):
print("Implemented abstract method")

obj = ConcreteClassExample()
obj.abstract_method() # Output: Implemented abstract method
obj.concrete_method() # Output: This is a concrete method

Abstract classes are useful for:


- Defining interfaces or base classes that can be shared by multiple
subclasses
- Enforcing certain methods or behaviors in subclasses
- Providing a way to group related classes and methods
Another example of abstract class is follows:
from abc import ABC, abstractmethod

class Animal(ABC):

@abstractmethod
def sound(self):
pass

@abstractmethod
def move(self):
pass

class Dog(Animal):

def sound(self):
return "Bark"

def move(self):
return "Run"

class Bird(Animal):

def sound(self):
return "Chirp"

def move(self):
return "Fly"

# The following will raise an error because you cannot instantiate an abstract
class
# animal = Animal()

# You can instantiate a subclass that implements all abstract methods


dog = Dog()
print(dog.sound()) # Output: Bark
print(dog.move()) # Output: Run

bird = Bird()
print(bird.sound()) # Output: Chirp
print(bird.move()) # Output: Fly

Inheritance

The method of inheriting the properties of parent class into a child class
is known as inheritance. It is an OOP concept. The following are the benefits
of inheritance.

 Code reusability- we do not have to write the same code, again and
again, we can just inherit the properties we need in a child class.
 It represents a real-world relationship between parent class and child
class.
 It is transitive in nature. If a child class inherits properties from
a parent class, then all other sub-classes of the child class will
also inherit the properties of the parent class.
Example :
class Parent():
def first(self):
print('first function')
class Child(Parent):
def second(self):
print('second function')
ob = Child()
ob.first()
ob.second()

Types Of Inheritance:
Depending upon the number of child and parent classes involved, there are
four types of inheritance in python.

Single Inheritance
When a child class inherits only a single parent class.

class Parent:
def func1(self):
print("this is function one")
class Child(Parent):
def func2(self):
print(" this is function 2 ")
ob = Child()
ob.func1()
ob.func2()

Multiple Inheritance
When a child class inherits from more than one parent class.
class Parent:
def func1(self):
print("this is function 1")
class Parent2:
def func2(self):
print("this is function 2")
class Child(Parent , Parent2):
def func3(self):
print("this is function 3")
ob = Child()
ob.func1()
ob.func2()
ob.func3()
Multilevel Inheritance
When a child class becomes a parent class for another child class.

class Parent:
def func1(self):
print("this is function 1")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child2(Child):
def func3("this is function 3")
ob = Child2()
ob.func1()
ob.func2()
ob.func3()

Hierarchical Inheritance
Hierarchical inheritance involves multiple inheritance from the same base or
parent class.

class Parent:
def func1(self):
print("this is function 1")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child2(Parent):
def func3(self):
print("this is function 3")
ob = Child()
ob1 = Child2()
ob.func1()
ob.func2()

Hybrid Inheritance
Hybrid inheritance involves multiple inheritances taking place in a single
program.

class Parent:
def func1(self):
print("this is function one")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child1(Parent):
def func3(self):
print(" this is function 3"):
class Child3(Parent , Child1):
def func4(self):
print(" this is function 4")
ob = Child3()
ob.func1()

Polymorphism

The word "polymorphism" means "many forms", and in programming it refers to


methods/functions/operators with the same name that can be executed on many
objects or classes. Polymorphism in python is a term used to refer to an
object’s ability to take on multiple forms. The term is derived from two
distinct terms: poly, which means numerous, and morphs, which means forms.
Polymorphism may be used in one of the following ways in an object-oriented
language:

Overloading of operators
Class Polymorphism in Python
Method overriding, also referred to as Run time Polymorphism
Method overloading, also known as Compile time Polymorphism

Magic Methods
In Python, special methods are also called magic methods, or dunder methods.
This latter terminology, dunder, refers to a particular naming convention
that Python uses to name its special methods and attributes. The convention
is to use double leading and trailing underscores in the name at hand, so it
looks like .__method__().
Sample magic methods are:-

#['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__',


'__delattr__',
#'__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__',
'__floordiv__',
#'__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__',
'__hash__',
#'__index__', '__init__', '__init_subclass__', '__int__', '__invert__',
'__le__',
#'__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__',
'__new__', '__or__',
#'__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__',
'__reduce_ex__',
#'__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__',
'__ror__', '__round__',
#'__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__',
'__rxor__', '__setattr__',
#'__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__',
'__trunc__', '__xor__', 'bit_length',

Access Modifier

Python uses the ‘_’ symbol to determine the access control for a specific
data member or a member function of a class. Access specifiers in Python
have an important role to play in securing data from unauthorized access and
in preventing it from being exploited.
A Class in Python has three types of access modifiers:
Public Access Modifier
Protected Access Modifier
Private Access Modifier

Sample Programs:-

You might also like