Why Use Classes?
Classes help you:
- ✅ Organize code
- ✅ Reuse code
- ✅ Store related data together
- ✅ Build large applications easily
- Class will have have two things properties & method
Syntax
class ClassName:
# Variables
# Functions (Methods)Creating an Object
class Car:
pass
car1 = Car()
print(car1)Here:
car1 is an object (instance) of the Car class.
Constructor (
__init__)- The constructor runs automatically when an object is created.
class Car:
def __init__(self):
print("Car Created")
car = Car()Output
Car CreatedWhat is
self?selfrefers to the current object.- Without
self, Python doesn't know which object's data you're referring to.
Example
class Student:
def __init__(self, name):
self.name = name
student = Student("Alice")
print(student.name)Output
AliceMethods
- Functions inside a class are called methods.
class Student:
def greet(self):
print("Hello")
student = Student()
student.greet()Output
HelloExample: Variables + Methods
class Student:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello", self.name)
student = Student("Alice")
student.greet()Output
Hello AliceQuick Summary
| Concept | Meaning |
|---|---|
| Class | Blueprint or template |
| Object | Instance of a class |
__init__() | Constructor, called automatically when an object is created |
self | Refers to the current object |
| Attribute | Variable inside a class |
| Method | Function inside a class |