1/3/23, 4:12 PM oops
In [1]:
###Creating Class and Object in Python
class Employee:
# class variables
company_name = 'ABC Company'
# constructor to initialize the object
def __init__(self, name, salary):###the __init__() method,
####we initialized the value of attributes.
###This method is called as soon as the object is created.
###The init method initializes the object.
# instance variables
[Link] = name
[Link] = salary
# instance method
def show(self):
print('Employee:', [Link], [Link], self.company_name)
# create first object
emp1 = Employee("DEEPA", 12000)
[Link]()
###create second object
emp2 = Employee("Nandhan",44444)
[Link]()
Employee: DEEPA 12000 ABC Company
Employee: Nandhan 44444 ABC Company
In [2]:
####Define class and instance attributes
class Cylinder:
# class attribute
pi = 3.14
def __init__(self, radius, height):
# instance variables
[Link] = radius
[Link] = height
if __name__ == '__main__':
c1 = Cylinder(4, 20)
c2 = Cylinder(10, 50)
print(f'Pi for c1:{[Link]} and c2:{[Link]}')
print(f'Radius for c1:{[Link]} and c2:{[Link]}')
print(f'Height for c1:{[Link]} and c2:{[Link]}')
print(f'Pi for both c1 and c2 is: {[Link]}')
Pi for c1:3.14 and c2:3.14
Radius for c1:4 and c2:10
Height for c1:20 and c2:50
Pi for both c1 and c2 is: 3.14
In [3]:
class Cylinder:
# class attribute
pi = 3.14
def __init__(self, radius, height):
# instance variables
[Link] = radius
[Link] = height
# instance method
localhost:8888/nbconvert/html/Desktop/PYTHON-MBU/[Link]?download=false 1/7
1/3/23, 4:12 PM oops
def volume(self):
return [Link] * [Link]**2 * [Link]
# class method
@classmethod
def description(cls):
return f'This is a Cylinder class that computes the volume using Pi={[Link]}
if __name__ == '__main__':
c1 = Cylinder(4, 2) # create an instance/object
print(f'Volume of Cylinder: {[Link]()}') # access instance method
print([Link]()) # access class method via class
print([Link]()) # access class method via instance
Volume of Cylinder: 100.48
This is a Cylinder class that computes the volume using Pi=3.14
This is a Cylinder class that computes the volume using Pi=3.14
In [4]:
class Employee:
def __init__(self, name, salary):
# public member
[Link] = name
# private member
# not accessible outside of a class
self.__salary = salary
def show(self):
print("Name is ", [Link], "and salary is", self.__salary)
emp = Employee("MAHA", 40000)
[Link]()
# access salary from outside of a class
print(emp.__salary)
Name is MAHA and salary is 40000
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5700/[Link] in <module>
14
15 # access salary from outside of a class
---> 16 print(emp.__salary)
AttributeError: 'Employee' object has no attribute '__salary'
In [ ]:
class Circle:
pi = 3.14
def __init__(self, redius):
[Link] = redius
def calculate_area(self):
print("Area of circle :", [Link] * [Link] * [Link])
class Rectangle:
def __init__(self, length, width):
[Link] = length
[Link] = width
def calculate_area(self):
print("Area of Rectangle :", [Link] * [Link])
localhost:8888/nbconvert/html/Desktop/PYTHON-MBU/[Link]?download=false 2/7
1/3/23, 4:12 PM oops
# function
def area(shape):
# call action
shape.calculate_area()
# create object
cir = Circle(5)
rect = Rectangle(10, 5)
# call common function
area(cir)
area(rect)
In [5]:
##USE OF INHERITANCE IN PYTHON
# Base class
class Vehicle:
def __init__(self, name, color, price):
[Link] = name
[Link] = color
[Link] = price
def info(self):
print([Link], [Link], [Link])
# Child class
class Car(Vehicle):
def change_gear(self, no):
print([Link], 'change gear to number', no)
# Create object of Car
car = Car('BMW X1', 'Black', 35000)
[Link]()
car.change_gear(5)
BMW X1 Black 35000
BMW X1 change gear to number 5
In [6]:
###Define a property that must have the same value for every class instance (object)
####Define a class attribute”color” with a default value white. I.e., Every Vehicle
class Vehicle:
# Class attribute
color = "White"
def __init__(self, name, max_speed, mileage):
[Link] = name
self.max_speed = max_speed
[Link] = mileage
class Bus(Vehicle):
pass
class Car(Vehicle):
pass
School_bus = Bus("School Volvo", 180, 12)
print(School_bus.color, School_bus.name, "Speed:", School_bus.max_speed, "Mileage:",
localhost:8888/nbconvert/html/Desktop/PYTHON-MBU/[Link]?download=false 3/7
1/3/23, 4:12 PM oops
car_new = Car("Audi Q5", 240, 18)
print(car_new.color, car_new.name, "Speed:", car_new.max_speed, "Mileage:", car_new.
White School Volvo Speed: 180 Mileage: 12
White Audi Q5 Speed: 240 Mileage: 18
In [7]:
from abc import ABC, abstractmethod
class Car(ABC):
def __init__(self,name):
[Link] = name
@abstractmethod
def price(self,x):
pass
obj = Car("Honda City")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5700/[Link] in <module>
8 def price(self,x):
9 pass
---> 10 obj = Car("Honda City")
TypeError: Can't instantiate abstract class Car with abstract method price
In [8]:
class Car(ABC):
def __init__(self,name):
[Link] = name
def description(self):
print("This the description function of class car.")
@abstractmethod
def price(self,x):
pass
class new(Car):
def price(self,x):
print(f"The {[Link]}'s price is {x} lakhs.")
obj = new("Honda City")
[Link]()
[Link](25)
This the description function of class car.
The Honda City's price is 25 lakhs.
EXCEPTION HANDLING
In [9]:
a=5
b=2
print(a/b)
print("Bye")
2.5
Bye
In [10]:
a=5
b=0
localhost:8888/nbconvert/html/Desktop/PYTHON-MBU/[Link]?download=false 4/7
1/3/23, 4:12 PM oops
print(a/b)
print("bye")
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5700/[Link] in <module>
1 a=5
2 b=0
----> 3 print(a/b)
4 print("bye")
ZeroDivisionError: division by zero
In [11]:
a=5
b=0
try:
print(a/b)
except Exception:
print("number can not be divided by zero")
print("bye")
number can not be divided by zero
bye
In [12]:
a=5
b=2
try:
print(a/b)
except Exception:
print("number can not be divided by zero")
print("bye")
2.5
In [13]:
a=5
b=0
try:
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("bye")
number can not be divided by zero division by zero
bye
In [14]:
a=5
b=2
try:
print("resource opened")
print(a/b)
print("resource closed")
except Exception as e:
print("number can not be divided by zero",e)
resource opened
2.5
resource closed
In [15]:
a=5
b=0
localhost:8888/nbconvert/html/Desktop/PYTHON-MBU/[Link]?download=false 5/7
1/3/23, 4:12 PM oops
try:
print("resource opened")
print(a/b)
print("resource closed")
except Exception as e:
print("number can not be divided by zero",e)
resource opened
number can not be divided by zero division by zero
In [16]:
a=5
b=0
try:
print("resource opened")
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("resource closed")
resource opened
number can not be divided by zero division by zero
resource closed
In [17]:
a=5
b=0
try:
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("the value can not be divided by zero",e)
finally:
print("resource closed")
resource open
the value can not be divided by zero division by zero
resource closed
In [19]:
a=5
b=3
try:
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("the value can not be divided by zero",e)
finally:
print("resource closed")
resource open
1.6666666666666667
enter a numberT
resource closed
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5700/[Link] in <module>
4 print("resource open")
5 print(a/b)
----> 6 k=int(input("enter a number"))
localhost:8888/nbconvert/html/Desktop/PYTHON-MBU/[Link]?download=false 6/7
1/3/23, 4:12 PM oops
7 print(k)
8 except ZeroDivisionError as e:
ValueError: invalid literal for int() with base 10: 'T'
In [20]:
a=5
b=0
try:
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("the value can not be divided by zero",e)
except ValueError as e:
print("invalid input")
except Exception as e:
print("something went wrong...",e)
finally:
print("resource closed")
resource open
the value can not be divided by zero division by zero
resource closed
In [21]:
try:
age=int(input("enter your age:"))
if age<0:
raise ValueError
print("yourage is",age)
except ValueError:
print("enter valid age")
print("rest of the code")
enter your age:5
yourage is 5
rest of the code
In [22]:
try:
age=int(input("enter your age:"))
if age<0:
raise ValueError
print("yourage is",age)
except ValueError:
print("enter valid age")
print("rest of the code")
enter your age:-7
enter valid age
rest of the code
In [ ]:
localhost:8888/nbconvert/html/Desktop/PYTHON-MBU/[Link]?download=false 7/7