HOME HTML EDITOR C JAVA PHP python

Python Classes and Objects

In Python, a class is a blueprint used to create objects. A class defines attributes (data) and methods (functions) that the objects created from it can use.

1. Creating a Class, __init__() & self

The __init__() method runs automatically whenever a new object is instantiated, and self refers to the current object instance:

class Student:
    def __init__(self, name, course):
        self.name = name
        self.course = course

    def introduce(self):
        return f"Hi, I am {self.name} learning {self.course}."

s1 = Student("Neha", "Python")
print(s1.introduce())  # Output: Hi, I am Neha learning Python.

2. Class Attributes vs. Instance Attributes

Class attributes are shared across all instances of a class, whereas instance attributes are unique to each object:

class Laptop:
    brand = "TechNova"  # Class attribute

    def __init__(self, model, ram_gb):
        self.model = model    # Instance attribute
        self.ram_gb = ram_gb  # Instance attribute

l1 = Laptop("AirBook 14", 16)
l2 = Laptop("ProBook 16", 32)

print(l1.brand, l1.model, l1.ram_gb)
print(l2.brand, l2.model, l2.ram_gb)

3. Modifying & Deleting Object Properties

You can update an object's attribute directly or remove an attribute using del:

s1.course = "Python & Django"
print("Updated course:", s1.course)

del s1.course
print("Has course attribute:", hasattr(s1, "course"))  # Output: False
Tip: Class names in Python conventionally follow PascalCase (such as StudentProfile or BankAccount), while method and variable names use snake_case.