class in python with Simple Example
1. What is a Class?
A class is a blueprint for creating objects.
Real-Life Example
Imagine a car factory:
- Class = Car blueprint
- Object = Actual car created from the blueprint
Syntax
class Car:
pass
This creates an empty class.
My Notes
*
2. Creating an Object
Objects are instances of a class.
Example
class Car:
pass
car1 = Car()
car2 = Car()
print(car1)
print(car2)
Output
<__main__.Car object at ...>
<__main__.Car object at ...>
Key Points
- Each object is independent.
- Objects are created using the class name followed by parentheses.
My Notes
*
3. Constructor (__init__)
The constructor runs automatically whenever an object is created.
Example
class Car:
def __init__(self):
print("Car Created")
car1 = Car()
Output
Car Created
Key Points
- Special method.
- Automatically called.
- Used to initialize object data.
My Notes
*
4. Understanding self
self refers to the current object.
Example
class Car:
def __init__(self):
self.brand = "Toyota"
car1 = Car()
print(car1.brand)
Output
Toyota
Key Points
- Represents the current object.
- Used to access variables and methods inside the class.
- Passed automatically by Python.
My Notes on self
5. Attributes (Variables Inside a Class)
Attributes store data related to an object.
Example
class Student:
def __init__(self):
self.name = "John"
self.age = 20
s1 = Student()
print(s1.name)
print(s1.age)
Output
John
20
My Notes
Learn more on Constructor vs attributes and passing values to attributes
6. Passing Values to Constructor
We can pass values when creating objects.
Example
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
s1 = Student("John", 20)
s2 = Student("Alice", 22)
print(s1.name)
print(s2.name)
Output
John
Alice
My Notes
*
7. Methods
Methods are functions inside a class.
Example
class Student:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello", self.name)
s1 = Student("John")
s1.greet()
Output
Hello John
My Notes
*
8. Multiple Methods
A class can have many methods.
Example
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
c = Calculator()
print(c.add(10, 5))
print(c.multiply(10, 5))
Output
15
50
My Notes
Understand how and why the Calculator without constructor, yes, that correct.
9. Instance Variables
Each object gets its own copy of instance variables.
Example
class Dog:
def __init__(self, name):
self.name = name
d1 = Dog("Tommy")
d2 = Dog("Rocky")
print(d1.name)
print(d2.name)
Output
Tommy
Rocky
My Notes
*
10. Class Variables
Class variables are shared by all objects.
Example
class Student:
school = "ABC School"
def __init__(self, name):
self.name = name
s1 = Student("John")
s2 = Student("Alice")
print(s1.school)
print(s2.school)
Output
ABC School
ABC School
My Notes
*
11. Instance Variables vs Class Variables
Example
class Student:
school = "ABC School"
def __init__(self, name):
self.name = name
s1 = Student("John")
print(s1.name)
print(s1.school)
Output
John
ABC School
Comparison
| Instance Variable | Class Variable |
|---|---|
| Unique to object | Shared by all objects |
| Stored in object | Stored in class |
| Created with self | Created directly in class |
My Notes
*
12. Class Methods
Used to work with class variables.
Example
class Student:
school = "ABC School"
@classmethod
def get_school(cls):
return cls.school
print(Student.get_school())
Output
ABC School
My Notes
Link on, understanding more in class methods vs instance methods
The
class methodcan access and modify class variables.
13. Static Methods
Static methods do not use object or class data.
Example
class Math:
@staticmethod
def add(a, b):
return a + b
print(Math.add(5, 3))
Output
8
My Notes
14. Encapsulation
Encapsulation means hiding internal data.
Example
class Bank:
def __init__(self):
self.__balance = 1000
Key Points
- Double underscore (
__) makes a variable private. - Prevents direct access.
My Notes
Link to understand more on encapsulation
15. Getters and Setters
Used to safely access and modify private variables.
Example
class Bank:
def __init__(self):
self.__balance = 1000
def get_balance(self):
return self.__balance
def set_balance(self, amount):
self.__balance = amount
My Notes
*
16. Inheritance
A child class inherits properties from a parent class.
Example
class Animal:
def eat(self):
print("Eating")
class Dog(Animal):
pass
d = Dog()
d.eat()
Output
Eating
My Notes
*
17. Types of Inheritance
Single Inheritance
class Father:
pass
class Son(Father):
pass
Multiple Inheritance
class Father:
pass
class Mother:
pass
class Child(Father, Mother):
pass
Multilevel Inheritance
class GrandFather:
pass
class Father(GrandFather):
pass
class Son(Father):
pass
My Notes
*
18. Method Overriding
A child class can replace a parent method.
Example
class Animal:
def sound(self):
print("Animal Sound")
class Dog(Animal):
def sound(self):
print("Bark")
d = Dog()
d.sound()
Output
Bark
My Notes
*
19. super()
Used to call parent class methods.
Example
class Animal:
def __init__(self):
print("Animal")
class Dog(Animal):
def __init__(self):
super().__init__()
print("Dog")
Output
Animal
Dog
My Notes
*
20. Polymorphism
Same method name, different behavior.
Example
class Dog:
def sound(self):
print("Bark")
class Cat:
def sound(self):
print("Meow")
animals = [Dog(), Cat()]
for animal in animals:
animal.sound()
Output
Bark
Meow
My Notes
*
21. Magic Methods
Special methods beginning and ending with __.
Common Magic Methods
| Method | Purpose |
|---|---|
__init__ |
Constructor |
__str__ |
String Representation |
__len__ |
Length |
__add__ |
Addition |
__eq__ |
Equality |
Example
def __str__(self):
return self.name
My Notes
*
22. Operator Overloading
Allows operators to work with custom objects.
Example
class Number:
def __init__(self, value):
self.value = value
def __add__(self, other):
return self.value + other.value
My Notes
*
23. Abstract Classes
Used to define required methods.
Example
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
My Notes
*
24. Composition
One class contains another class.
Example
class Engine:
pass
class Car:
def __init__(self):
self.engine = Engine()
My Notes
*
25. Real-World Project Example
Bank Account
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def show_balance(self):
print(self.balance)
My Notes
*
Revision Checklist
- Class
- Object
- Constructor
- self
- Attributes
- Methods
- Instance Variables
- Class Variables
- Class Methods
- Static Methods
- Encapsulation
- Getters & Setters
- Inheritance
- Method Overriding
- super()
- Polymorphism
- Magic Methods
- Operator Overloading
- Abstract Classes
- Composition