UNIT 3 Notes of PYTHON
UNIT 3 Notes of PYTHON
UNIT 3 Notes of PYTHON
Class
Class is called as the blueprint for the object. If you want to create a class then
you need to use class keyword then write the name of the class and finally give
a colon(:).
Syntax:
class ClassName:
statemen-1
statemen-2
statemen-3
statement-n
Object
Objects are the instantiation of classes and also the way to use classes.
These are those entities that have attributes and behaviors which are defined
inside the class.
When we create a class, then we only describe the blueprint for objects but
memory is allocated when we create objects of classes.
Syntax
class ClassName:
pass
obj = ClassName()
Here, ClassName is the name of the class, and obj is the object of the class.
Example
class Employee:
# class attribute
company = "copyassignment.com"
# constructor
# instance attributes
self.name = name
self.age = age
self.salary = salary
# creating objects
Class Attribute
We create a class with name “Employee“. Variables that we create in a class
are called class attributes and here, the company is a class attribute.
Constructor
Then, we have created the constructor. A constructor is a special method in a
class that the python always calls when we create or instantiate an object.
Python uses “__init__()” to create a constructor.
The self parameter
The __init__() method can take parameters but the first parameter should
always be the “self” parameter which refers to the current instance of the
class.
You can use any name instead of self but it should be the first parameter
always.
Instance Attribute
Variables that we create inside a constructor are called instance attributes.
These attributes are different for different instances. Like here name, age,
and salary are different for both emp1 and emp2 instances.
Methods
Methods are the functions that are defined inside the body of a class and
associated with an object. They are used to define the behaviors of an object.
Example
class Employee:
# class attribute
company = "copyassignment.com"
# constructor
# instance attributes
self.name = name
self.age = age
self.salary = salary
# class method
def myMethod1(self):
print(f"Hi {self.name}!")
# creating objects
# calling methods
emp1.myMethod1()
emp1.myMethod2("London")
Output
Hi John!
1. Inheritance (IMP)
Reusability of code – since one can inherit from the base class, the efficiency of
the code increases and the size of the code also decreases instead of rewriting
the code.
It forms a chain process i.e. if a child class is inherited from the base class, and if
a new class is inherited from the child class, then all the properties of the base
class will also be present in the new class.
Syntax:
Class base_class:
Body of base_class
Body of child_class
Example
class Parent:
self.firstname = fname
self.age = fage
def view(self):
print(self.firstname , self.age)
class Child(Parent):
def view(self):
print(self.firstname ," came ", self.age , " years ago. Today, python is
the base for" , self.lastname)
Output
Python came 28 years ago. Today, python is the base for Machine Learning
Types of inheritance:
Single inheritance
Multiple inheritance
Multilevel inheritance
Hierarchical inheritance
Hybrid inheritance
Single inheritance
In single inheritance, only one child class can be inherited from the base class.
Not more than one class can be used for inheritance.
Syntax:
Class base_class:
Body of base_class
Body of child_class
Example
class Employee:
company = "Google"
def showDetails(self):
print("This is an employee")
class Programmer(Employee):
language = "Python"
# company = "Youtube"
def getLanguage(self):
print(f"The language is {self.language}")
# def showDetails(self):
# print("This is an programmer")
e = Employee()
e.showDetails()
p = Programmer()
p.showDetails()
print(p.company)
Output
This is an employee
This is an employee
Multiple inheritance
In multiple inheritance, a child class can be inherited from more than one base
class. Unlike single inheritance, there is no restriction on the number of base
classes for inheriting the properties.
Syntax:
Class Base1():
Body of base1
Class of Base2():
Body of base2
Body of child
Example
class Freelancer:
company = "Fiverr"
level = 0
def upgradeLevel(self):
self.level = self.level + 1
print(self.level)
class Employee:
company = "Visa"
eCode = 120
p = Programmer()
p.upgradeLevel()
print(p.company)
Output
1
Fiverr
Multilevel inheritance
Syntax:
Class Base:
class Employee(Person):
company = "Honda"
def getSalary(self):
print(f"Salary is {self.salary}")
def takeBreath(self):
print("I am an Employee so I am luckily breathing..")
class Programmer(Employee):
company = "Fiverr"
def getSalary(self):
print(f"No salary to programmers")
def takeBreath(self):
print("I am a Progarmmer so I am breathing++..")
p = Person()
p.takeBreath()
# print(p.company) # throws an error
e = Employee()
e.takeBreath()
print(e.company)
pr = Programmer()
pr.takeBreath()
print(pr.company)
print(pr.country)
OUTPUT:
I am breathing...
I am an Employee so I am luckily breathing..
Honda
I am a Progarmmer so I am breathing++..
Fiverr
India
Hierarchical inheritance
Example
Python program to demonstrate
# Hierarchical inheritance
# Base class
class Parent:
def func1(self):
# Derived class1
class Child1(Parent):
def func2(self):
# Derivied class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Output:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.
Hybrid inheritance
# hybrid inheritance
class School:
def func1(self):
class Student1(School):
def func2(self):
class Student2(School):
def func3(self):
def func4(self):
# Driver's code
object = Student3()
object.func1()
object.func2()
Output:
This function is in school.
This function is in student 1.
2.Constructors(IMP)
Constructors are generally used for instantiating an object. The task of
constructors is to initialize(assign values) to the data members of the class
when an object of the class is created. In Python the __init__() method is
called the constructor and is always called when an object is created.
Syntax of constructor declaration :
def __init__(self):
# body of the constructor
Types of constructors :
default constructor: The default constructor is a simple constructor
which doesn’t accept any arguments. Its definition has only one argument
which is a reference to the instance being constructed.
parameterized constructor: constructor with parameters is known as
parameterized constructor. The parameterized constructor takes its first
argument as a reference to the instance being constructed known as self
and the rest of the arguments are provided by the programmer.
Example of default constructor :
Python3
class GeekforGeeks:
# default constructor
def __init__(self):
self.geek = "GeekforGeeks"
def print_Geek(self):
print(self.geek)
# creating object of the class
obj = GeekforGeeks()
obj.print_Geek()
Output :
GeekforGeeks
class Addition:
first = 0
second = 0
answer = 0
# parameterized constructor
self.first = f
self.second = s
def display(self):
print("First number = " + str(self.first))
def calculate(self):
# perform Addition
obj.calculate()
# display result
obj.display()
Output :
First number = 1000
Second number = 2000
Addition of two numbers = 3000
3.Polymorphism in Python(IMP)
The word polymorphism means having many forms. In programming,
polymorphism means the same function name (but different signatures)
being used for different types. The key difference is the data types and
number of arguments used in function.
Example of inbuilt polymorphic functions:
Python3
# morphic functions
print(len("geeks"))
Output:
5
3
Python3
class India():
def capital(self):
def type(self):
class USA():
def capital(self):
def language(self):
def type(self):
def func(obj):
obj.capital()
obj.language()
obj.type()
obj_ind = India()
obj_usa = USA()
func(obj_ind)
func(obj_usa)
Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
4.Abstraction in Python(IMP)
Abstraction in python is defined as a process of handling complexity by hiding
unnecessary information from the user. This is one of the core concepts of object-oriented
programming (OOP) languages. That enables the user to implement even more complex
logic on top of the provided abstraction without understanding or even thinking about all the
hidden background/back-end complexity.
Importance:
Syntax
Example -
Output:
Explanation -
In the above code, we have imported the abc module to create the abstract base
class. We created the Car class that inherited the ABC class and defined an abstract
method named mileage(). We have then inherited the base class from the three
different subclasses and implemented the abstract method differently. We created
the objects to call the abstract method.
print("Geeks"+"For")
print(3 * 4)
print("Geeks"*4)
Output
3
GeeksFor
12
GeeksGeeksGeeksGeeks
class A:
self.a = a
ob1 = A(1)
ob2 = A(2)
ob3 = A("Geeks")
ob4 = A("For")
print(ob1 + ob2)
print(ob3 + ob4)
print(A.__add__(ob1 , ob2))
print(A.__add__(ob3,ob4))
print(ob1.__add__(ob2))
print(ob3.__add__(ob4))
Output
3
GeeksFor
3
GeeksFor
3
GeeksFor
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors
are the problems in a program due to which the program will stop the
execution. On the other hand, exceptions are raised when some internal
events occur which changes the normal flow of the program.
OUTPUT:
Enter a number: 0
division by zero
except ValueError as e:
print("Please Enter a valid value")
except ZeroDivisionError as e:
print("Make sure you are not dividing by 0")
OUTPUT:
Enter a number: 0
Make sure you are not dividing by 0
Thanks for using this code!
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
try:
i = int(input("Enter a number: "))
c = 1/i
except Exception as e:
print(e)
exit()
finally:
print("We are done")
OUTPUT:
Enter a number: 0
division by zero
We are done
7.Multithreading in Python(IMP)
Consider the diagram below to understand how multiple threads exist in memory:
Consider the diagram below in which a process contains two active threads:
Multi-threading in Python
In Python, the threading module provides a very simple and intuitive API for
spawning multiple threads in a program. Let us consider a simple example using a
threading module:
Python3
# of threading
import threading
def print_cube(num):
def print_square(num):
if __name__ =="__main__":
# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
# starting thread 1
t1.start()
# starting thread 2
t2.start()
t2.join()
print("Done!")
Square: 100
Cube: 1000
Done!
Let us try to understand the above code:
To import the threading module, we do:
import threading
To create a new thread, we create an object of Thread class. It takes following
arguments:
target: the function to be executed by thread
args: the arguments to be passed to the target function
To start a thread, we use start method of Thread class.
t1.start()
t2.start()
Once the threads start, the current program (you can think of it like a main thread)
also keeps on executing. In order to stop execution of current program until a
thread is complete, we use join method.
t1.join()
t2.join()
As a result, the current program will first wait for the completion of t1 and then t2.
Once, they are finished, the remaining statements of current program are executed.
Consider the diagram below for a better understanding of how above program works:
Consider the python program given below in which we print thread name and
corresponding process for each task:
The diagram given below clears the above concept: