In Python, you create a class using the class keyword, followed by the class name (by convention, in PascalCase) and a colon. Inside the class, you define attributes (variables) and methods (functions) that describe the behavior of the objects created from that class.
Hereβs a structured example:
# Define a class
class Employee:
# Constructor (__init__) β runs when an object is created
def __init__(self, name, salary):
self.name = name # public attribute
self.__salary = salary # private attribute
# Method to display employee info
def display_info(self):
print(f"Employee Name: {self.name}, Salary: {self.__salary}")
# Getter for private attribute (Encapsulation)
def get_salary(self):
return self.__salary
# Setter for private attribute
def set_salary(self, amount):
if amount > 0:
self.__salary = amount
Creating Objects #
Once the class is defined, you can create instances (objects) of the class:
emp1 = Employee("Aswini", 5000)
emp2 = Employee("Kumar", 10000)
Accessing Methods and Attributes #
emp1.display_info() # Employee Name: Aswini, Salary: 5000
print(emp2.get_salary()) # 10000
emp2.set_salary(12000)
print(emp2.get_salary()) # 12000
Key Points #
__init__constructor: Initializes object attributes when a new object is created.- Public and private attributes: Public (e.g.,
name) can be accessed directly; private (e.g.,__salary) are accessed via getters/setters. - Methods: Functions defined inside a class describe behavior of objects.
self: Represents the current instance of the class and is used to access attributes and methods.
Practical Use #
Iβve used classes like this in a reporting system to represent users, reports, and notifications. Each report was an object with attributes like title, data, and status, and methods like generate() or send_email(). Using classes made the code modular and reusable, especially when scaling to handle multiple report types.
