Lesson 49 of 70 – Python Classes
70%

Python Classes

A class is a blueprint or template used to create objects in Python. A class can contain variables, called attributes, and functions, called methods, that define the properties and behavior of objects.

Note: A class is created using the class keyword in Python.

Creating a Class

We use the class keyword to create a class.

class Student:

    name = "Rahul"
    age = 20

Here, Student is the class name and name and age are class attributes.

Class Naming Convention

Class names are commonly written using PascalCase, where each word starts with a capital letter.

class Student:
    pass


class BankAccount:
    pass


class EmployeeDetails:
    pass

Using pass in a Class

If a class does not contain any code yet, we can use the pass statement as a placeholder.

class Student:
    pass

The class can be completed later.

Creating an Object

An object is created by calling the class like a function.

class Student:

    name = "Rahul"


student1 = Student()

print(student1.name)

Output:

Rahul

Creating Multiple Objects

A single class can be used to create multiple objects.

class Student:

    name = "Rahul"


student1 = Student()
student2 = Student()

print(student1.name)
print(student2.name)

Output:

Rahul
Rahul

Class Attributes

Variables defined directly inside a class are called class attributes. They can be accessed through the class or its instances.

class Student:

    school = "Soopro Pathshala"


print(Student.school)

student1 = Student()

print(student1.school)

Output:

Soopro Pathshala
Soopro Pathshala

Instance Attributes

Instance attributes belong to individual objects. They are commonly created inside __init__() using self.

class Student:

    def __init__(self, name, age):

        self.name = name
        self.age = age


student1 = Student("Rahul", 20)

student2 = Student("Amit", 22)

print(student1.name)
print(student2.name)

Output:

Rahul
Amit

The __init__() Method

The __init__() method is commonly used to initialize an object with values when it is created.

class Student:

    def __init__(self, name, age):

        self.name = name
        self.age = age


student = Student("Rahul", 20)

print(student.name)
print(student.age)

The self Parameter

The self parameter refers to the current instance of the class. It allows an instance method to access instance attributes and other instance methods.

class Student:

    def __init__(self, name):

        self.name = name


    def display(self):

        print(self.name)


student = Student("Rahul")

student.display()

Output:

Rahul

Methods in a Class

A method is a function defined inside a class. Methods usually operate on object or class data.

class Student:

    def display(self):

        print("Welcome to Python")


student = Student()

student.display()

Output:

Welcome to Python

Method with Parameters

A class method can accept parameters in addition to self.

class Calculator:

    def add(self, a, b):

        return a + b


calculator = Calculator()

result = calculator.add(10, 20)

print(result)

Output:

30

Changing Object Attributes

An instance attribute can be changed after an object has been created.

class Student:

    def __init__(self, name):

        self.name = name


student = Student("Rahul")

print(student.name)

student.name = "Amit"

print(student.name)

Output:

Rahul
Amit

Adding an Attribute to an Object

Python allows attributes to be added to an individual object.

class Student:

    pass


student = Student()

student.name = "Rahul"
student.age = 20

print(student.name)
print(student.age)

Output:

Rahul
20

Deleting an Attribute

The del keyword can be used to remove an attribute from an object.

class Student:

    def __init__(self):

        self.name = "Rahul"
        self.age = 20


student = Student()

del student.age

print(student.name)

Output:

Rahul

Deleting an Object

The del keyword can also remove a reference to an object.

class Student:

    name = "Rahul"


student = Student()

print(student.name)

del student

After del student, that variable no longer refers to the object.

Class Variable Example

A class variable is shared through the class and can be accessed by instances unless an instance attribute with the same name shadows it.

class Student:

    school = "Soopro Pathshala"


student1 = Student()
student2 = Student()

print(student1.school)
print(student2.school)

Output:

Soopro Pathshala
Soopro Pathshala

Modifying a Class Variable

A class variable can be changed through the class itself.

class Student:

    school = "Old School"


student1 = Student()
student2 = Student()

Student.school = "Soopro Pathshala"

print(student1.school)
print(student2.school)

Output:

Soopro Pathshala
Soopro Pathshala

Class Method

A class method uses the @classmethod decorator and receives the class as its first argument, usually named cls.

class Student:

    school = "Soopro Pathshala"


    @classmethod
    def show_school(cls):

        print(cls.school)


Student.show_school()

Output:

Soopro Pathshala

Static Method

A static method uses the @staticmethod decorator. It does not receive self or cls automatically.

class Calculator:

    @staticmethod
    def multiply(a, b):

        return a * b


print(Calculator.multiply(5, 4))

Output:

20

Class Inheritance

A class can inherit attributes and methods from another class. The new class is called the child class, and the existing class is called the parent class.

class Animal:

    def speak(self):

        print("Animal makes a sound")


class Dog(Animal):

    pass


dog = Dog()

dog.speak()

Output:

Animal makes a sound

Method Overriding

A child class can provide its own implementation of a method inherited from the parent class. This is called method overriding.

class Animal:

    def sound(self):

        print("Animal sound")


class Dog(Animal):

    def sound(self):

        print("Bark")


dog = Dog()

dog.sound()

Output:

Bark

Using super()

The super() function can be used to call methods or initialization logic from a parent class.

class Person:

    def __init__(self, name):

        self.name = name


class Student(Person):

    def __init__(self, name, course):

        super().__init__(name)

        self.course = course


student = Student("Rahul", "Python")

print(student.name)
print(student.course)

Output:

Rahul
Python

Class Properties

Python provides the @property decorator for creating methods that can be accessed like attributes.

class Student:

    def __init__(self, name):

        self._name = name


    @property
    def name(self):

        return self._name


student = Student("Rahul")

print(student.name)

Output:

Rahul

Class Documentation

A class can have a documentation string, also called a docstring, to describe its purpose.

class Student:
    """Represents a student."""

    pass


print(Student.__doc__)

Output:

Represents a student.

Complete Class Example

class Student:

    school = "Soopro Pathshala"


    def __init__(self, name, age, course):

        self.name = name
        self.age = age
        self.course = course


    def display(self):

        print("Name:", self.name)
        print("Age:", self.age)
        print("Course:", self.course)
        print("School:", self.school)


student1 = Student(
    "Rahul",
    20,
    "Python"
)

student1.display()

Output:

Name: Rahul
Age: 20
Course: Python
School: Soopro Pathshala

Advantages of Classes

  • Classes help organize related data and behavior.
  • They make it possible to create multiple similar objects.
  • They support code reuse through inheritance.
  • They help structure large applications.
  • They support encapsulation and abstraction.
  • They make real-world entities easier to model.

Key Points

  • A class is a blueprint for creating objects.
  • A class is created using the class keyword.
  • An object is created by calling the class.
  • The __init__() method is commonly used to initialize objects.
  • The self parameter refers to the current instance.
  • Attributes store data associated with a class or object.
  • Methods are functions defined inside a class.
  • @classmethod creates a class method.
  • @staticmethod creates a static method.
  • Python classes can use inheritance and method overriding.
  • super() can access parent-class behavior.

🧠 Quick Quiz

Question: Which keyword is used to create a class in Python?