In Python, classes are the primary tool for implementing object-oriented programming (OOP). They allow you to define objects with specific attributes and behaviors, encapsulate logic, and build modular, reusable code. This article provides a step-by-step overview of how classes work in Python and how to use them effectively.
To define a class, use the class keyword:
class Person:
passThis creates a class named Person with no attributes or methods yet.
The __init__ method initializes object attributes when an instance is created:
class Person:
def __init__(self, name, age):
self.name = name
self.age = ageHere, name and age are assigned when a new Person object is created.
p1 = Person("Ali", 30)
print(p1.name) # Output: AliThis creates an instance p1 with its own data.
Methods define behaviors for class instances:
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, my name is {self.name}")p2 = Person("Sara")
p2.greet() # Output: Hello, my name is SaraInheritance allows a class to extend another class:
class Employee(Person):
def __init__(self, name, salary):
super().__init__(name)
self.salary = salaryEmployee inherits from Person and adds a new attribute salary.
Use _ or __ to define private attributes:
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def get_balance(self):
return self.__balance__balance is private and accessible only through methods.
Use decorators to define class-level or static methods:
class Math:
@staticmethod
def add(x, y):
return x + y
@classmethod
def identity(cls):
return cls.__name__Classes in Python are essential for building structured, scalable, and maintainable code. By mastering constructors, methods, inheritance, and encapsulation, developers can create powerful object-oriented systems that are easy to extend and debug.