Notes

Class in Python [ English ]

< Prev Next >

1. Introduction

A class in Python is a user-defined blueprint or template used to create objects. It is a fundamental concept of Object-Oriented Programming (OOP).

A class defines:

Objects are instances of a class.

2. Definition of Class

A class is a collection of:

It groups related data and functions together.

3. Syntax of Class

class ClassName:
    # attributes (variables)

    def method_name(self):
        # code

4. Creating a Class

class Student:
    name = "Rahul"

5. Creating an Object

class Student:
    name = "Rahul"

s1 = Student()
print(s1.name)

Output

Rahul

6. Understanding self

7. Using Constructor (__init__ Method)

7.1 What is Constructor?

A constructor is a special method that is automatically called when an object is created.


7.2 Syntax

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

7.3 Example

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

s1 = Student("Rahul", 20)

print(s1.name)
print(s1.age)

Output

Rahul
20

8. Adding Methods in Class

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

    def display(self):
        print("Name:", self.name)

s1 = Student("Amit")
s1.display()

Output

Name: Amit

9. Types of Variables in Class

9.1 Instance Variables

self.name = name

9.2 Class Variables

class Student:
    school = "ABC School"

10. Example with Class Variable

class Student:
    school = "ABC School"

    def __init__(self, name):
        self.name = name

s1 = Student("Rahul")
s2 = Student("Amit")

print(s1.school)
print(s2.school)

11. Object-Oriented Concepts (Brief)

Classes help implement:

12. Summary

< Prev Next >