Python Classes/Objects


Python is an object-oriented programming language.
Almost everything in Python is an object.


🔹 Create a Class

Use the class keyword to create a class.

class MyClass:
    x = 10

🔹 Create an Object

Create an object from a class using the class name with parentheses.

obj = MyClass()
print(obj.x)  # Output: 10

🔹 The __init__() Function

The __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)

🔹 The self Parameter

The 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()

🔹 Modify Object Properties

You can modify property values after object creation.

p1.age = 30
print(p1.age)

🔹 Add Object Methods

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()

🔹 Delete Object Properties

Use del to delete properties or entire objects.

del p1.age  # Delete property
del p1      # Delete object

Practice Questions

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.


Go Back Top