Python Object and Classes
In Python, everything is considered an object. Python is an object-oriented programming language that supports the creation and manipulation of objects. An object is an instance of a class. A class is like a blueprint for creating objects, while an object is a concrete instance of the data and behavior defined in that class.
What is a Class?
A class in Python is a user-defined data structure that bundles data and functionality together. Classes define attributes (variables) and methods (functions) that are common to all objects of that class. Think of a class as a template for creating multiple objects with similar properties and behaviors.
- Attributes: Characteristics or properties that describe the object (e.g., name, age, color).
- Methods: Functions that define the behavior of the object (e.g., actions the object can perform).
What is an Object?
An object is an instance of a class. When a class is defined, no memory is allocated until an object is created from it. Each object can have its own unique values for the attributes defined in the class.
For example, if you have a class called Car
, you can create multiple car objects like car1
, car2
, etc., each with its own specific attribute values (e.g., color, model, brand).
Creating a Class and Object in Python
Let's look at how to create a class and an object in Python.
# Creating a class
class Car:
# Constructor method
def __init__(self, brand, model, color):
self.brand = brand
self.model = model
self.color = color
# Method to display car details
def display_info(self):
print(f"Brand: {self.brand}, Model: {self.model}, Color: {self.color}")
# Creating objects of the Car class
car1 = Car("Toyota", "Corolla", "Red")
car2 = Car("Honda", "Civic", "Blue")
# Accessing object attributes and methods
car1.display_info() # Output: Brand: Toyota, Model: Corolla, Color: Red
car2.display_info() # Output: Brand: Honda, Model: Civic, Color: Blue
Output
Explanation of Code Example
In the above code:
- We defined a class named
Car
with a constructor method__init__()
that initializes the attributesbrand
,model
, andcolor
. - The
display_info()
method is used to print the details of the car object. - We created two objects,
car1
andcar2
, each with different attribute values. - The
display_info()
method is called for each object to print its details.
Class Attributes vs Instance Attributes
In Python, there are two types of attributes:
- Class Attributes: These are variables defined within the class but outside any method. They are shared among all objects of the class.
- Instance Attributes: These are variables that are specific to each object. They are defined inside methods, typically inside the
__init__()
constructor method.
Example of Class and Instance Attributes
class Animal:
# Class attribute
kingdom = "Animalia"
def __init__(self, species, name):
# Instance attributes
self.species = species
self.name = name
# Creating objects
dog = Animal("Canine", "Buddy")
cat = Animal("Feline", "Whiskers")
# Accessing class and instance attributes
print(dog.kingdom) # Output: Animalia
print(dog.species) # Output: Canine
print(cat.kingdom) # Output: Animalia
print(cat.name) # Output: Whiskers
Output
Understanding the self
Keyword
The self
keyword is used to represent the instance of a class. It binds the attributes with the given arguments and is used to access variables and methods within the class.
_ _init_ _ method
In order to make an instance of a class in Python, a specific function called __init__ is called. Although it is used to set the object's attributes, it is often referred to as a constructor. The self-argument is the only one required by the __init__ method. This argument refers to the newly generated instance of the class. To initialise the values of each attribute associated with the objects, you can declare extra arguments in the __init__ method.
Benefits of Using Classes and Objects
- Modularity: Classes allow you to group related data and functions together, making your code more organized and modular.
- Reusability: You can reuse classes to create multiple objects, reducing redundancy.
- Ease of Maintenance: With classes, it becomes easier to maintain and update the code as it grows in complexity.
- Encapsulation: Helps in protecting the internal state of the object by restricting direct access to its attributes.
Understanding the concept of classes and objects is fundamental to learning Object-Oriented Programming (OOP) in Python. Classes allow you to create structured and reusable code, making it easier to build complex software systems. By using attributes and methods, you can define the properties and behaviors of objects, leading to more efficient and maintainable code.