Back to Python Course

Python Course

Python supports Object-Oriented Programming (OOP), allowing you to model real-world entities using classes and objects.

What is a Class?

A class is a blueprint for creating objects. It defines a data structure that contains:

  • Attributes (data)
  • Methods (functions) that describe the behavior of the objects.

Think of a class as a template for creating multiple objects with similar properties and behaviors.

Syntax

class ClassName: def __init__(self, parameters): self.attribute = value # instance attribute def method(self): # code block

What is an Object?

An object is an instance of a class. It is a concrete entity created based on the class blueprint. Each object has its own unique data stored in attributes and can perform actions defined by the class methods.

Example: Defining and Using the Person Class

Creating the Class

class Person: def __init__(self, name, age): self.name = name # instance attribute self.age = age # instance attribute def greet(self): print(f"Hi, I’m {self.name} and I’m {self.age} years old.")
  • __init__ method is the constructor, automatically called when a new object is created.
  • self refers to the current object instance.
  • name and age are parameters to initialize the object's attributes.
  • greet() is an instance method that can access attributes using self.

Creating Objects (Instances)

p1 = Person("Praveen", 39) # Creating an object of class Person p2 = Person("Kiran", 40) # Another object with different values

Calling Methods

p1.greet() # Output: Hi, I’m Praveen and I’m 39 years old. p2.greet() # Output: Hi, I’m Kiran and I’m 40 years old.

Besides instance methods (which work on individual objects), Python supports:

Class Methods

  • Use the decorator @classmethod.
  • Takes cls as the first parameter (refers to the class itself, not an instance).
  • Can access and modify class-level data (shared by all instances).
class Person: population = 0 # class attribute def __init__(self, name, age): self.name = name self.age = age Person.population += 1 @classmethod def get_population(cls): return cls.population

Static Methods

  • Use the decorator @staticmethod.
  • Does not take self or cls as the first parameter.
  • Behaves like a regular function inside the class namespace.
  • Useful for utility functions related to the class but not tied to instance or class data.
class MathHelper: @staticmethod def add(x, y): return x + y print(MathHelper.add(5, 3)) # Output: 8

Inheritance

Inheritance allows a class (called the child or subclass) to inherit attributes and methods from another class (called the parent or superclass). This helps reuse code and create a hierarchy of classes.

Why Use Inheritance?

  • To avoid code duplication
  • To extend or modify behaviors of existing classes
  • To create more specific versions of a general class

Syntax of Inheritance

class ParentClass: # parent class code class ChildClass(ParentClass): # child class code (inherits from ParentClass)

Example

Let's imagine we are building a system to manage different types of vehicles. All vehicles have some common features like make, model, and year. But specific types like Cars and Bikes have unique features or behaviors.

class Vehicle: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def start_engine(self): print(f"The engine of {self.make} {self.model} is starting.") def stop_engine(self): print(f"The engine of {self.make} {self.model} is stopping.") class Car(Vehicle): def __init__(self, make, model, year, num_doors): super().__init__(make, model, year) self.num_doors = num_doors def open_trunk(self): print(f"Opening trunk of {self.make} {self.model}.") class Bike(Vehicle): def __init__(self, make, model, year, has_carrier): super().__init__(make, model, year) self.has_carrier = has_carrier def ring_bell(self): print(f"{self.make} {self.model} bell rings: Ring Ring!")

Using the classes:

car1 = Car("Toyota", "Camry", 2023, 4) bike1 = Bike("Trek", "FX 3", 2021, True) car1.start_engine() # The engine of Toyota Camry is starting. car1.open_trunk() # Opening trunk of Toyota Camry. bike1.start_engine() # The engine of Trek FX 3 is starting. bike1.ring_bell() # Trek FX 3 bell rings: Ring Ring!

Why is this useful?

  • Code Reuse: Car and Bike reuse common code from Vehicle (make, model, year, start/stop engine).
  • Extend Functionality: Each subclass adds its unique features (open_trunk() for Car, ring_bell() for Bike).
  • Maintainability: Changes to common features only need to be made in one place (Vehicle).