[go: up one dir, main page]

0% found this document useful (0 votes)
109 views23 pages

Oop Assignment

Uploaded by

rupak15-4751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views23 pages

Oop Assignment

Uploaded by

rupak15-4751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

dict = {

"Name": "Rupak",
"Dept": "CSE",
"ID": 4751
}
print(dict)
{'Name': 'Rupak', 'Dept': 'CSE', 'ID': 4751}
dict = {
"Name": "Rupak",
"Dept": "CSE",
"ID": 4751,
"ID": 799
}
print(dict)
{'Name': 'Rupak', 'Dept': 'CSE', 'ID': 799}
dict = {
"Name": "Rupak",
"Dept": "CSE",
"ID": 4751,
"ID": 799
}
print(len(dict))

dict = {
"Name": "Rupak",
"Dept": "CSE",
"ID": 4751,
"ID": 799
}
print(dict)
dict["Name"] = "Rupak1"
print(dict)

{'Name': 'Rupak', 'Dept': 'CSE', 'ID': 799}

dict = {
"Name": "Rupak",
"Dept": "CSE",
"ID": 4751,
"ID": 799
}
print(dict.values())
print(dict.keys())
print(dict.items())
dict_values(['Rupak', 'CSE', 799])
dict_keys(['Name', 'Dept', 'ID'])

dict_items([('Name', 'Rupak'), ('Dept', 'CSE'), ('ID', 799)])


dict = {
"Name": "Rupak",
"Dept": "CSE",
"ID": 4751,
"ID": 799
} if "Name" in dict: print("Yes, 'Name' is one of the keys in the
thisdict dictionary")
Yes, 'Name' is one of the keys in the thisdict dictionary
dict = {
"Name": "Rupak",
"Dept": "CSE",
"ID": 4751,
"ID": 799
}
dict.update({"CGPA" : 3.99})
print(dict)
{'Name': 'Rupak', 'Dept': 'CSE', 'ID': 799, 'CGPA': 3.99}
dict = {
"Name": "Rupak",
"Dept": "CSE",
"ID": 4751,
"ID": 799
}
dict.pop("ID")
print(dict)
dict.popitem()
print(dict)
{'Name': 'Rupak', 'Dept':
'CSE'}
{'Name':
'Rupak'}
Ques-01 : What is a class in Python, and how is it different from an object?
Ans : In Python, a class is like a blueprint of objects. Objects are created using
class. A class contains set of properties or attributes and methods, by assigning
values to these an object is created. After defining a class, it can be used as a
template for creating multiple objects. A class does not contain actual data
valuesin it.
On the other hand, objects are the real world entity, instance of a class. When a
class is defined, no memory is allocated until an object is created from the class.
Each object can have different values for the properties defined by the class.
So, a class is a template or blueprint of an object and an object is an instance of a
class.

Ques-02 : What is the purpose of the __init__ method in a Python class?


Ans : The ‘__init__’ method is commonly reffered as constructor in python. It is a
special method used to initialize newly created objects from a class. This method is
automatically called right after the object’s creation.It can set up values of
attributes. So, the ‘__init__’ method is fundamental for initializing new objects in
python.

Ques-03 : How do you create an instance (object) of a class in Python?


Ans : Creating an object of a class in Python:
Defining the classs : First we define a class using ‘class’ keyword with a class name
and a colon. Inside the class, methods and attributes are defined of objects
created from the class.
Instantiating the class : To create an instance of the class, we simply call the class
using its name followed by the parentheses. If the class’s ‘__init__’ method
accepts the parameters, the other values will be passed into the parameters.
Example: class Car: def
__init__(self,clr,model):
self.clr=clr
self.model=model
def display(self):
print(‘Car color :’ , self.clr)
print(‘Car model :’ , self.model) my_car =
Car(“Black”,”Corollla”) my_car.display()

Ques-04: What is the significance of the self parameter in Python class methods?
Ans : The “self” parameter plays a crucial role in Python. It provides a way to
access the attributes and metods of the class in which it is used. It allows an
object’s methods to access and manipulate the object’s instance variables and
other methods. It must be the first parameter of any method in the class. Also,
“self” helps to differentiate instance attributes from local vcariables.
#Rupak

#ID-221-15-4751

#Creating an Empty Class in Python


class cat: pass

#Creating an Object
obj = cat()

#Creating a class and object with class and instance attributes


class Dog: attr1 = "mammal"
def __init__(self,
name):
self.name = name
Rock = Dog("Rock")
Tommy = Dog("Tommy")

# Accessing class attributes


print("Rock is a {}".format(Rock.__class__.attr1))
print("Tommy is also a {}".format(Tommy.__class__.attr1))

# Accessing instance attributes print("My


name is {}".format(Rock.name)) print("My
name is {}".format(Tommy.name))

Rock is a mammal
Tommy is also a mammal
My name is Rock
My name is Tommy

#Creating Classes and objects with methods


class Dog:

# class attribute
attr1 = "mammal"

# Instance attribute
def __init__(self, name):
self.name = name
def speak(self): print("My
name is {}".format(self.name))

# Driver code
# Object instantiation
Rock = Dog("Rock")
Tommy = Dog("Tommy")
# Accessing class methods
Rock.speak()
Tommy.speak()

My name is Rock
My name is Tommy

#Inheritance in Python
# Python code to demonstrate how parent constructors
# are called.

# parent class class


Person(object):

# __init__ is known as the constructor


def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber

def display(self):
print(self.name)
print(self.idnumber)
def details(self): print("My
name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))

# child class class Employee(Person): def


__init__(self, name, idnumber, dept, type):
self.dept = dept self.type = type

# invoking the __init__ of the parent class


Person.__init__(self, name, idnumber)
def details(self): print("My
name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.type))

# creation of an object variable or an instance


a = Employee('Rupak', 4751, 'CSE', "Student")

# calling a function of the class Person using


# its instance
a.display()
a.details()
Rupak
4751
My name is Rupak
IdNumber: 4751
Post: Student

#Polymorphism in Python
class Bird:
def
type(self):
print("There are many types of birds.")

def fly(self):
print("Most of the birds can fly but some cannot.")

class sparrow(Bird):
def
fly(self):
print("Sparrows can fly.")

class ostrich(Bird):

def fly(self):
print("Ostriches cannot fly.")

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

obj_bird.type()
obj_bird.fly()

obj_spr.type()
obj_spr.fly()

obj_ost.type()
obj_ost.fly()

There are many types of birds.


Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.

#Encapsulation in Python

# Creating a class class Base:


def __init__(self):
self.a = "Hello World"
self.__c = "I am Pythone Programming Language"

# Creating a derived class


class Derived(Base):
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)

# Driver code
obj1 = Base()
print(obj1.a)

# Uncommenting print(obj1.c) will


# raise an AttributeError

# Uncommenting obj2 = Derived() will


# also raise an AtrributeError as
# private member of base class
# is called inside derived class

Hello World
April 30, 2024

Area: 20 Perimeter: 18

Rectangle 2: Area: 21 Perimeter: 20

[ ]:

1
April 30, 2024

Name: Messi, Age: 23 Student ID: 221-15-4751

[ ]:

1
April 30, 2024

Area of circle: 28.274333882308138

[ ]:

1
class Shape: def
calculate_area(self):
pass

class Rectangle(Shape): def


__init__(self, width, height):
self.width = width self.height
= height
def calculate_area(self):
return self.width * self.height

class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
pi = 3.141592653589793
return pi * self.radius ** 2

rectangle = Rectangle(5, 4)
circle = Circle(3)

print("Area of rectangle:", rectangle.calculate_area())


print("Area of circle:", circle.calculate_area())
Area of rectangle: 20

Area of circle: 28.274333882308138


1
Name: Tahmid, Age: 24
Employee ID: 4751
Name: Rupak, Age: 20 Student ID:
1234
assignment-on-exception

May 21, 2024

Cell In[5], line 2


print("a)
^
SyntaxError: unterminated string literal (detected at line 2)

--------------------------------------------------------------------
-------
TypeError Traceback (most recent call last)
Cell In[6], line 4
2 x=3
3 y="Hello"
----> 4 x+y z=
5 print(z)

TypeError: unsupported operand type(s) for +: 'int' and 'str'


--------------------------------------------------------------------
-------
IndexError Traceback (most recent call last)
Cell In[8], line 3
1 #IndexError
2 list = [1,2,3]
----> 3 list[4] print( )

IndexError: list index out of range

--------------------------------------------------------------------
-------
ZeroDivisionError Traceback (most recent call last)
Cell In[9], line 4
2 x=4
3 y=0
----> 4 x/y z=
5 print('z')

ZeroDivisionError: division by zero

--------------------------------------------------------------------
-------
NameError Traceback (most recent call last)
Cell In[10], line 3
1 x=3
2 y="Hello"
----> 3 print(z)

NameError: name 'z' is not defined

[ ]:

1
Cat sound: Meow

[ ]:
print("Man city ")
Man city
def func():
print("Forca Barca")
func()
Forca Barca
a=1 b="Hi"
c="Hello"
print(a,b,c)
1 Hi Hello
print(b+c)
HiHello
print(a,b)
1 Hi
def func(x,y):
print(x , " is " , y)

func("Am", "jam")
Am is jam
def func(*x): print(x[0] ,
" is " , x[1])

func("Am", "jam")
Am is jam
def func_arb(*x1): print(x1[0] + "," + x1[1], "and",
x1[2], "are bestus")

func_arb("Rupak","Rupak1","Rupak2")
Rupak,Rupak1 and Rupak2 are
bestus
def func(x,y): print(x, "and",
y, "are frnds")

func(x='Rupak', y='Rupak1')
Rupak and Rupak1 are frnds

1
def func(**x):
print(x['a'],x['b'],x['c'],x['d'])

func(a='j', b='U', c='S1', d='S2')


j U S1 S2
def func(x='BD'):
print(x, 'is love')
func()
func('Spain')
func('Argentina')
func('Germany')

BD is love
Spain is love
Argentina is love
Germany is love

def func(frnd1,frnd2,frnd3):
print(f"{frnd1} is my close friend.")

func(frnd1 = "Rupak", frnd2 = "Rupak1",frnd3 = "Rupak2")


Rupak is my close friend.
def pow(x):
return x**2

print(pow(2))
print(pow(4))
print(pow(6))

4
16
36

def func(w, x, /, *, y, z):


print(w + x + y + z) func(100,
15 , y = 98, z = 221)
434
print(4751)
4751
f= ['am', 'jam', 'kadol', 'kola','kola']
print(f) print(len(f))

['am', 'jam', 'kadol', 'kola', 'kola']


5

print(f[1:6])
print(f[2:6])
print(f[3:])
print(f[:])
['jam', 'kadol', 'kola', 'kola']
['kadol', 'kola', 'kola']
['kola', 'kola']

['am', 'jam', 'kadol', 'kola', 'kola']


f= ['am', 'jam', 'kadol', 'kola','kola']

for i in f:
print(f)
['am', 'jam', 'kadol', 'kola', 'kola']
['am', 'jam', 'kadol', 'kola', 'kola']
['am', 'jam', 'kadol', 'kola', 'kola']
['am', 'jam', 'kadol', 'kola', 'kola']
['am', 'jam', 'kadol', 'kola', 'kola']
f= ['am', 'jam', 'kadol', 'kola','kola']

for i in f:
print(i)

am
jam
kadol
kola
kola

tuple= ('am', 'jam', 'kadol')


x=list(tuple) x[0]='kauua-
kadol' print(x)

['kauua-kadol', 'jam', 'kadol']


(a,b,c)= tuple

print(a)
print(tuple[1])

am
jam

tuple= ('am', 'jam', 'kadol')


(a,b,c)= tuple
print(a)
print(b)
print(c)

am
jam
kadol

x=[1,2,3,4,5]
y=4

if y in x:
print(True)
True
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)
('a', 'b', 'c', 1, 2, 3)
x=int(input())
y=[1990,1991,1990,1990,1992,1991]
y1=[]

for i in y:
x1=x-i
y1.append(x1)
print(y1)
2024

[34, 33, 34, 34, 32, 33]


l=[7,3,13,6,8,5,1,2,4,15,9,10,12,14,11]
l1=int(input()) ln=[i for i in l if
i<l1]
ln.sort()
print(ln)

11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

x=[(1,2,3), (4,5,6)]
for i in x:
print(i,end='')
(1, 2, 3)(4, 5, 6)
l1=[1,2,3]
l2=['am', 'jam', 'kola']
l3=l1 l4=l2.copy()
print(l3) for i in l4:
print(i,' ', end='')
[1, 2, 3]

am jam kola
l2.append(l1)
print(l2)
['am', 'jam', 'kola', [1, 2, 3]]
l1=[1,2,3] l2=['am',
'jam', 'kola']

for i in l2:
l1.append(i)
print(l1)
[1, 2, 3, 'am', 'jam', 'kola']
l1=[1,2,3] l2=['am',
'jam', 'kola']

for i in l2:
l1.append(l2)
print(l1)
[1, 2, 3, ['am', 'jam', 'kola'], ['am', 'jam', 'kola'], ['am', 'jam',
'kola']]

l1=[1,2,3]
l2=['am', 'jam', 'kola']

l1.extend(l2)
print(l1)
[1, 2, 3, 'am', 'jam', 'kola']
f2=['mwssi', 'ron']
f3=f2+l2 print(f3)
['mwssi', 'ron', 'am', 'jam', 'kola']

You might also like