Unit 5
Unit 5
Classes:
Python is a programming language that focuses on object-oriented
programming. In Python, almost everything is an object. We can check if the
python is an object using the type(). It is just a collection of variables and Python
functions. There are various types of objects in Python such as Lists, dictionaries,
files, sets, strings and etc. An object is defined by its class. For example, an integer
variable is a member of the integer class. An object is a physical entity. The
properties of an object are as follows. State, Identity, and behavior are the three
key properties of the object.
The definition of Python class is simply a logical entity that behaves as a prototype
or a template to create objects. Python classes provide methods that could be used
to modify an object’s state. They also specify the qualities that an object may
possess.
Ex:
a = 28
print(type(a))
#<class 'int'>
l = [1,2,3]
print(type(l))
#<class 'list'>
The new object belongs to the List class. From the object, we can call
methods, already pre-built in Python. To see all the methods allowed in the object,
we use the dir() function
dir(l)
What is a Class?
The class can be defined as a collection of objects that define the common
attributes and behaviors of all the objects.
What is an Object?
The object is an entity that has state and behavior. It is an instance of a class
that can access the data.
Self-Variable:
Here, the self is used as a reference variable, which refers to the current class
object. It is always the first argument in the function definition. However,
using self is optional in the function call.
class Employee:
id = 10
name = "Devansh"
def display (self):
print(self.id,self.name)
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.
Methods:
Constructor Method:
class Person:
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Josh')
p.say_hi()
Ex:
Initializer method __init__, called in this way because it’s the method that
initializes the attributes of the object. Moreover, it is automatically called once
the object is created.
Magical methods are special methods with double underscores on both sides. For
example, __add__ and __mul__ are used to respectively sum and multiplicate
objects of the same class, while __repr__ returns a representation of the object
as a string.
Instance methods are methods that belong to the object created. For
example, l.append(4) adds an element at the end of the list.
In addition to the code shown previously, the initializer method __init__ is used to
initialize the attributes of the Dog class.
Initializer method
class Dog:
def __init__(self,name,breed,age):
self.Name = name
self.Breed = breed
self.Age = age
print("Name: {}, Breed: {}, Age: {}".format(self.Name,
self.Breed,self.Age))
jack = Dog('Jack','Husky',5)
print(jack)
print(jack.Age)
Magical Method
class Dog:
def __init__(self,name,breed,age):
self.Name = name
self.Breed = breed
self.Age = age
def __repr__(self):
return "Name: {}, Breed: {}, Age: {}".format(self.Name,
self.Breed,self.Age)
jack = Dog('Jack','Husky',5)
print(jack)
Instance Method
class Dog:
def __init__(self,name,breed,age,tired):
self.Name = name
self.Breed = breed
self.Age = age
self.Tired = tired
def __repr__(self):
return "Name: {}, Breed: {}, Age: {}".format(self.Name,
self.Breed,self.Age)
def Sleep(self):
if self.Tired==True:
return 'I will sleep'
else:
return "I don't want to sleep"
Inheritance:
Ex:
class polygon:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
class square(polygon):
def __init__(self, side):
polygon.__init__(self, side, side)
MySquare = square(3)
print(MySquare.area())
Overriding Methods:
# Constructor
def __init__(self):
self.value = "Inside Parent"
# Constructor
def __init__(self):
self.value = "Inside Child"
# Driver's code
obj1 = Parent()
obj2 = Child()
obj1.show()
obj2.show()
Multiple Inheritance: When a class is derived from more than one base class it is
called multiple Inheritance.
# Driver's code
obj = Child()
obj.show()
obj.display()
class Parent():
# Driver code
g = GrandChild()
g.show()
g.display()
Using Super(): Python super() function provides us the facility to refer to the parent
class explicitly. It is basically useful where we have to call superclass functions. It
returns the proxy object that allows us to refer parent class by ‘super’.
# super()
class Parent():
def show(self):
print("Inside Parent")
class Child(Parent):
def show(self):
Data Hiding:
Ex:
class CounterClass:
__privateCount = 0
def count(self):
self.__privateCount += 1
print(self.__privateCount)
counter = CounterClass()
counter.count()
counter.count()
print(counter.__privateCount)
counter.count()
counter.count()
print(counter.CounterClass__privatecounter)
1. Syntax errors
2. Logical errors (Exceptions)
When the proper syntax of the language is not followed then a syntax error
is thrown.
amount = 10000
# check that You are eligible to purchase Dsa Self Paced or not
if(amount>2999)
print("You are eligible to purchase Dsa Self Paced")
When in the runtime an error that occurs after passing the syntax test is
called exception or logical type. For example, when we divide any number by zero
then the ZeroDivisionError exception is raised, or when we import a module that
does not exist then ImportError is raised.
# initialize the amount variable
marks = 10000
Exception
Exceptions are those which can be handled at the run time whereas errors
cannot be handled.
In Python, we catch exceptions and handle them using try and except code
blocks. The try clause contains the code that can raise an exception, while
the except clause contains the code lines that handle the exception. Let's see
if we can access the index from the array, which is more than the array's
length, and handle the resulting exception.
Ex:
a = ["Python", "Exceptions", "try and except"]
try:
#looping through the elements of the array a, choosing a range that goes beyond
the length of the array
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed by the
Python interpreter
except:
print ("Index out of range")
Handling Exception:
Raising Exceptions:
If a condition does not meet our criteria but is correct according to the
Python interpreter, we can intentionally raise an exception using the raise keyword.
We can use a customized exception in conjunction with the statement.
https://intellipaat.com/blog/tutorial/python-tutorial/python-classes-and-objects/
#no1
https://www.javatpoint.com/python-exception-handling