-
Hajipur, Bihar, 844101
Python is an object-oriented programming language.
Almost everything in Python is an object.
Use the class
keyword to create a class.
class MyClass:
x = 10
Create an object from a class using the class name with parentheses.
obj = MyClass()
print(obj.x) # Output: 10
__init__()
FunctionThe __init__()
function is called automatically when the object is created.
It is used to assign values to object properties.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Alice", 25)
print(p1.name)
print(p1.age)
self
ParameterThe self
parameter refers to the current instance.
It is used to access variables and methods within the class.
class Car:
def __init__(self, model):
self.model = model
def show(self):
print("Car model is:", self.model)
c1 = Car("Tesla")
c1.show()
You can modify property values after object creation.
p1.age = 30
print(p1.age)
Objects can also have methods (functions inside a class).
class Student:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello", self.name)
s = Student("John")
s.greet()
Use del
to delete properties or entire objects.
del p1.age # Delete property
del p1 # Delete object
Q1. Write a Python program to create a class named Laptop
with properties brand
and price
.
Q2. Write a Python program to use the __init__()
method to initialize the properties of the Laptop
class.
Q3. Write a Python program to create two objects of the Laptop
class and print their details.
Q4. Write a Python program to add a method discount()
that reduces the price by a given amount or percentage.
Q5. Write a Python program to modify the value of the price
property after the object is created.
Q6. Write a Python program to add a method that returns a full description of the laptop (e.g., brand and price).
Q7. Write a Python program to create a class Teacher
with attributes name
and subject
.
Q8. Write a Python program to use self
to access and print the teacher’s information inside a method.
Q9. Write a Python program to delete the subject
property of a Teacher
object using the del
keyword.
Q10. Write a Python program to delete the entire object of the Teacher
class using the del
keyword.
Q1: What is a class in Python?
Q2: What is an object?
Q3: What is the purpose of the __init__() function?
Q4: What does the self keyword refer to?
Q5: Which keyword is used to define a class?
Q6: What is required when creating an object?
Q7: Can a class have multiple objects?
Q8: What can objects contain?
Q9: How can you remove a property from an object?
Q10: What happens if you try to print a deleted object?