What Are Classes and Objects in Python?
- Class: A class is a blueprint for creating objects. It defines the structure and behavior that the objects of the class will have.
- Object: An object is an instance of a class. It represents a specific entity with attributes (data) and methods (functions).
Analogy
Think of a class as a blueprint for a house. The blueprint specifies what the house will look like (attributes) and how it will function (methods). An object is the actual house built using that blueprint.
Syntax for Defining a Class
class ClassName:
# Class attributes and methods go here
Creating an Object
# Creating an object from a class
object_name = ClassName()
Example: Defining a Simple Class and Creating an Object
# Defining a class
class Car:
def __init__(self, brand, model): # Constructor method
self.brand = brand
self.model = model
def display_info(self): # Method to display information
print(f"Car Brand: {self.brand}, Model: {self.model}")
# Creating an object of the Car class
my_car = Car("Toyota", "Corolla")
# Accessing the object's method
my_car.display_info() # Outputs: Car Brand: Toyota, Model: Corolla
Key Concepts of Classes and Objects
- Attributes: Attributes store the state or data of an object. They are defined using instance variables or class variables.
- Methods: Methods define the behavior of an object. They are functions defined within a class.
- Constructor (__init__): A special method called when an object is created. It initializes the object’s attributes.
Understanding Instance and Class Variables
- Instance Variables: Unique to each object. Defined inside the constructor (__init__).
- Class Variables: Shared across all objects of a class. Defined directly inside the class but outside any method.
Example: Instance and Class Variables
class Dog:
species = "Canis familiaris" # Class variable
def __init__(self, name, age): # Constructor
self.name = name # Instance variable
self.age = age # Instance variable
# Creating objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Bella", 5)
# Accessing variables
print(dog1.species) # Outputs: Canis familiaris
print(dog1.name) # Outputs: Buddy
Object Methods in Python
Methods define what an object can do. They take self as the first parameter, referring to the object itself.
Example: Object Methods
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
# Creating an object
rect = Rectangle(10, 5)
print(f"Area: {rect.area()}") # Outputs: Area: 50
Inheritance in Python
Inheritance allows a class (child class) to derive attributes and methods from another class (parent class).
Syntax for Inheritance
class ParentClass:
# Parent class attributes and methods
class ChildClass(ParentClass):
# Child class attributes and methods
Example: Inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
class Dog(Animal):
def speak(self):
return f"{self.name} barks."
# Creating objects
generic_animal = Animal("Animal")
dog = Dog("Rex")
print(generic_animal.speak()) # Outputs: Animal makes a sound.
print(dog.speak()) # Outputs: Rex barks.
Encapsulation in Python
Encapsulation hides the internal state of an object and allows controlled access through methods.
Private Attributes
Attributes can be made private by prefixing their names with double underscores (__).
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def get_balance(self):
return self.__balance
# Creating an object
account = BankAccount(1000)
print(account.get_balance()) # Outputs: 1000
Polymorphism in Python
Polymorphism allows different objects to use the same interface while behaving differently.
Example: Polymorphism
class Bird:
def fly(self):
return "Birds can fly."
class Penguin(Bird):
def fly(self):
return "Penguins can't fly."
# Using polymorphism
for animal in [Bird(), Penguin()]:
print(animal.fly())
# Outputs:
# Birds can fly.
# Penguins can't fly.
Key Benefits of Using Classes and Objects
- Code Reusability: Write code once and reuse it multiple times.
- Modularity: Organize code into separate classes, making it easier to maintain and debug.
- Encapsulation: Protect data by restricting direct access.
- Inheritance and Polymorphism: Extend functionality without rewriting code.