Python Classes and Objects

🐍 Python Classes and Objects — Complete Guide

Python is an Object-Oriented Programming (OOP) language, and classes and objects are the foundation of OOP.


📌 What is a Class?

A class is a blueprint or template used to create objects.
It defines attributes (variables) and methods (functions).


📌 What is an Object?

An object is an instance of a class.
Using a class, you can create multiple objects with the same structure but different data.



✅ Creating a Class

class Student:
name = "John"
age = 20

✅ Creating an Object

s1 = Student()
print(s1.name)
print(s1.age)

🧠 Multiple Objects Example

s1 = Student()
s2 = Student()

print(s1.name)
print(s2.name)



🏗 Using __init__() Constructor

The __init__() method automatically runs when you create an object.

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

p1 = Person("Alice", 25)
print(p1.name)
print(p1.age)


🔍 Self Keyword Explained

  • self refers to the current object.

  • Helps access variables and methods of the class.



🎯 Adding Methods in Class

class Car:
def __init__(self, model):
self.model = model

def display(self):
print("Car Model:", self.model)

c = Car("BMW")
c.display()



🧩 Updating Object Properties

c = Car("Tesla")
c.model = "Audi"
print(c.model)


❌ Deleting Object Properties

del c.model

❌ Deleting Entire Object

del c


⚙ Class Attributes vs Instance Attributes

class Laptop:
company = "Dell" # class attribute

def __init__(self, ram):
self.ram = ram # instance attribute

l1 = Laptop("8GB")
l2 = Laptop("16GB")

print(l1.company, l1.ram)
print(l2.company, l2.ram)



🏗 Example: Real-Life Class

class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary

def info(self):
print(f"Employee: {self.name}, Salary: {self.salary}")

e1 = Employee("Raj", 50000)
e1.info()



🔥 Object Methods Calling Other Methods

class Calculator:
def add(self, a, b):
return a + b

def result(self):
print("Sum is", self.add(5, 10))

c = Calculator()
c.result()



⭐ Summary

Feature Description
Class Blueprint
Object Instance of class
Attributes Variables inside class
Methods Functions inside class
__init__() Constructor (auto runs)
self Refers to current object

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *