Python Classes and Objects

Python is an object-oriented programming language. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made.

Example 1: Defining a Simple Class

Create a class named Person with an attribute name and a method to display it.

# Defining a simple class
class Person:
    def __init__(self, name):
        self.name = name
    def display_name(self):
        print("Name:", self.name)

person = Person("Karthick AG")
person.display_name()

Name: Karthick AG

Example 2: Class with Multiple Attributes

Create a Student class with attributes name, age, and grade.

# Class with multiple attributes
class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade
    def display_info(self):
        print(f"Name: {self.name}, Age: {self.age}, Grade: {self.grade}")

student = Student("Rohini", 20, "A")
student.display_info()

Name: Rohini, Age: 20, Grade: A

Example 3: Class with Methods

Create a Calculator class with methods to add and subtract numbers.

# Class with methods
class Calculator:
    def add(self, a, b):
        return a + b
    def subtract(self, a, b):
        return a - b

calc = Calculator()
print("Addition:", calc.add(10, 5))
print("Subtraction:", calc.subtract(10, 5))

Addition: 15

Subtraction: 5

Example 4: Private Attributes and Methods

Demonstrate the use of private attributes using name mangling.

# Private attributes
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance
    def deposit(self, amount):
        self.__balance += amount
    def __display_balance(self):
        print("Balance:", self.__balance)

account = BankAccount(1000)
account.deposit(500)
# Accessing private method (not recommended)
account._BankAccount__display_balance()

Balance: 1500

Example 5: Class Variables

Create a class variable shared among all instances of the class.

# Class variables
class Employee:
    company_name = "Tech Solutions"
    def __init__(self, name):
        self.name = name

emp1 = Employee("Durai")
emp2 = Employee("Vijay")
print(emp1.name, "works at", emp1.company_name)
print(emp2.name, "works at", emp2.company_name)

Durai works at Tech Solutions

Vijay works at Tech Solutions

Example 6: Object Methods and Self Parameter

Understand the use of the self parameter in methods.

# Using self parameter
class Country:
    def __init__(self, name):
        self.name = name
    def show_country(self):
        print("Country:", self.name)

india = Country("India")
india.show_country()

Country: India

Explanation: Classes are blueprints for creating objects. The __init__ method initializes the object's attributes, and methods define its behaviors. The self parameter refers to the instance of the class.