-
Hajipur, Bihar, 844101
Python supports Object-Oriented Programming (OOP) which lets you structure code using classes and objects.
A class is a blueprint.
An object is an instance of the class.
class Car:
def __init__(self, brand):
self.brand = brand
mycar = Car("Tesla")
print(mycar.brand) # Tesla
__init__()
ConstructorThe __init__()
method runs automatically when the object is created.
class Person:
def __init__(self, name):
self.name = name
self
Keywordself
refers to the current instance of the class.
class Student:
def __init__(self, name):
self.name = name
def greet(self):
print("Hi, " + self.name)
s1 = Student("Amit")
s1.greet() # Hi, Amit
s1.name = "Ravi"
print(s1.name)
del s1.name
del s1
A class can inherit from another class.
class Animal:
def speak(self):
print("Sound")
class Dog(Animal):
def bark(self):
print("Woof")
d = Dog()
d.speak() # Sound
d.bark() # Woof
Use super()
to call the parent class's constructor.
class Animal:
def __init__(self):
print("Animal created")
class Dog(Animal):
def __init__(self):
super().__init__()
print("Dog created")
Hide internal details using private attributes:
class Account:
def __init__(self):
self.__balance = 1000 # private
a = Account()
# print(a.__balance) # Error
Different classes can define the same method differently.
class Bird:
def sound(self):
print("Tweet")
class Cat:
def sound(self):
print("Meow")
Q1. Write a Python program to create a Book
class with attributes title
and author
.
Q2. Write a Python program to add a method display()
in the Book
class to show book information.
Q3. Write a Python program to create multiple objects of the Book
class and call the display()
method for each.
Q4. Write a Python program to create a base class Employee
and a derived class Manager
that inherits from Employee
.
Q5. Write a Python program to use super()
in the Manager
class to call the parent constructor.
Q6. Write a Python program to add a private variable in a class (using __var
) and restrict direct access from outside the class.
Q7. Write a Python program to implement a sound()
method in two different classes (e.g., Dog
, Cat
) and use polymorphism to call them.
Q8. Write a Python program to change the value of an object property after the object has been created.
Q9. Write a Python program to delete a property of an object using del
.
Q10. Write a Python program to create a class with both class-level and object-level attributes, and print both.
Q1: What is a class in Python?
Q2: What is the role of the __init__() method?
Q3: What does the self keyword refer to?
Q4: What is inheritance in Python?
Q5: What does encapsulation mean in OOP?
Q6: Which keyword is used to access a parent class in Python?
Q7: What does polymorphism allow?
Q8: What is an object?
Q9: How is a private variable typically defined?
Q10: What is the main advantage of using OOP?