In Python, classes and objects are fundamental concepts of Object-Oriented Programming (OOP). They allow you to create reusable, organized code by structuring it into entities that represent real-world objects.
Classes
A class is like a blueprint for creating objects. It defines a set of attributes (data) and methods (functions) that the objects created from the class will have.
Example:
class Car:
# Initializer or constructor to set up initial attributes
def __init__(self, companyName, color):
self.companyName = companyName # attribute
self.color = color # attribute
# Method
def start(self):
print(f"The {self.color} {self.companyName} car is starting.")
Objects
An object is an instance of a class. When you create an object, you are creating an individual item based on the class blueprint.
# Creating an object of the Car class
my_car = Car("Tata", "White")
# Accessing attributes
print(my_car.companyName) # Output: Tata
print(my_car.color) # Output: White
# Calling a method
my_car.start() # Output: The White Tata car is starting.
Key Concepts
Attributes: These are the properties of an object, defined in the __init__
method of a class.
Methods: These are functions defined within a class that describe the behaviors of an object.
Constructor (__init__
method): This special method initializes the attributes of an object when it is created.
Self parameter: Refers to the instance of the class itself, allowing access to its attributes and methods.
Example of Classes and Objects
class Pet:
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
# Creating an object
my_dog = Pet("Tommy", 7)
# Accessing methods
my_dog.name() # Output: Tommy
print(my_dog.get_age()) # Output: 7
Why use class and Object?
Classes and objects are useful for creating organized, modular, and maintainable code in larger programs.
Modularity: Code is more modular, which makes it easier to manage.
Reusability: You can create multiple objects from a single class.
Encapsulation: Classes encapsulate data and functions, protecting and organizing them.