You are on page 1of 7

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
self.name = name
self.salary = salary

# instance method
def show(self):
print('Employee:', self.name, self.salary, self.company_name)

# create first object


emp1 = Employee("DEEPA", 12000)
emp1.show()

###create second object


emp2 = Employee("Nandhan",44444)
emp2.show()

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
self.radius = radius
self.height = height

if __name__ == '__main__':
c1 = Cylinder(4, 20)
c2 = Cylinder(10, 50)

print(f'Pi for c1:{c1.pi} and c2:{c2.pi}')


print(f'Radius for c1:{c1.radius} and c2:{c2.radius}')
print(f'Height for c1:{c1.height} and c2:{c2.height}')
print(f'Pi for both c1 and c2 is: {Cylinder.pi}')

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
self.radius = radius
self.height = height

# instance method
localhost:8888/nbconvert/html/Desktop/PYTHON-MBU/oops.ipynb?download=false 1/7
1/3/23, 4:12 PM oops

def volume(self):
return Cylinder.pi * self.radius**2 * self.height

# class method
@classmethod
def description(cls):
return f'This is a Cylinder class that computes the volume using Pi={cls.pi}

if __name__ == '__main__':
c1 = Cylinder(4, 2) # create an instance/object

print(f'Volume of Cylinder: {c1.volume()}') # access instance method


print(Cylinder.description()) # access class method via class
print(c1.description()) # 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
self.name = name
# private member
# not accessible outside of a class
self.__salary = salary

def show(self):
print("Name is ", self.name, "and salary is", self.__salary)

emp = Employee("MAHA", 40000)


emp.show()

# 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/516387326.py 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):


self.radius = redius

def calculate_area(self):
print("Area of circle :", self.pi * self.radius * self.radius)

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

def calculate_area(self):
print("Area of Rectangle :", self.length * self.width)

localhost:8888/nbconvert/html/Desktop/PYTHON-MBU/oops.ipynb?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):


self.name = name
self.color = color
self.price = price

def info(self):
print(self.name, self.color, self.price)

# Child class
class Car(Vehicle):

def change_gear(self, no):


print(self.name, 'change gear to number', no)

# Create object of Car


car = Car('BMW X1', 'Black', 35000)
car.info()
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):


self.name = name
self.max_speed = max_speed
self.mileage = 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/oops.ipynb?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):
self.name = name

@abstractmethod
def price(self,x):
pass
obj = Car("Honda City")

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5700/1783280137.py 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):
self.name = 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 {self.name}'s price is {x} lakhs.")
obj = new("Honda City")

obj.description()
obj.price(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/oops.ipynb?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/3861058488.py 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/oops.ipynb?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/945494406.py in <module>
4 print("resource open")
5 print(a/b)
----> 6 k=int(input("enter a number"))

localhost:8888/nbconvert/html/Desktop/PYTHON-MBU/oops.ipynb?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/oops.ipynb?download=false 7/7

You might also like