Understanding Classes and Objects in Python:

What is a Class?

  • In Python, a class is like a blueprint or model for creating objects.
  • It contains both data (attributes) and actions (methods) that define the object’s behavior.

How to Define a Class?

  • Use the class keyword followed by the class name.
  • Optionally, include a documentation string to describe the class.

Example:

class Student:
    """This is a student class."""
    
    def __init__(self, name, age, marks):
        self.name = name
        self.age = age
        self.marks = marks
        
    def talk(self):
        print("Hello, I am", self.name)
        print("My age is", self.age)
        print("My marks are", self.marks)

What is an Object?

  • An object is an instance of a class, representing a specific entity.
  • You can create multiple objects from the same class.

How to Create an Object?

  • Use the class name followed by parentheses.
  • Assign it to a reference variable to access its properties and methods.

Example:

s1 = Student("John", 20, 85)
s1.talk()

Understanding Self Variable:

  • self is a reference to the current object within a class method.
  • It is used to access instance variables and methods of the object.

Constructor Concept:

  • A constructor is a special method (__init__) used for initializing object attributes.
  • It is called automatically when an object is created.
  • It initializes instance variables.
  • Each object has its own constructor, which executes only once during object creation.
  • Constructor is optional and if we are not providing any constructor then python will provide default constructor.

Example:

class Student:
def __init__(self, name, rollno, marks):
self.name = name
self.rollno = rollno
self.marks = marks

s1 = Student("John", 101, 85)

Simplified Example:

Let’s simplify this further with a practical example:

class Car:
"""A simple class to represent a car."""

def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year

def info(self):
print(f"This is a {self.year} {self.brand} {self.model}.")

# Creating objects of Car class
car1 = Car("Toyota", "Camry", 2020)
car2 = Car("Honda", "Civic", 2018)

# Accessing object methods
car1.info()
car2.info()

This code defines a Car class with attributes for brand, model, and year. It also has a method info() to display car information. Then, it creates two car objects (car1 and car2) and calls the info() method on each to display their information.

Leave a comment