Classes
A class is a blueprint. The __init__ method runs when you create an object, and self refers to the instance itself.
Basic Class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Alice", 25)
print(p1.name, p1.age)
Try it Yourself โ
Methods
Methods are functions defined inside a class. They always take self as the first parameter.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
r = Rectangle(4, 5)
print(r.area())
print(r.perimeter())
Try it Yourself โ
Class vs Instance Variables
Class variables are shared by all instances; instance variables belong to each object.
class Employee:
company = "TechCorp"
def __init__(self, name):
self.name = name
e1 = Employee("Alice")
e2 = Employee("Bob")
print(e1.company, e1.name)
print(e2.company, e2.name)
Employee.company = "NewCorp"
print(e1.company)
Try it Yourself โ