In the realm of object-oriented programming, classes and objects are fundamental components. They represent the two primary foundations of OOP (Object-Oriented Programming). A class functions as a custom-defined template for generating objects, whereas objects are particular instances that are derived from that template.
Class in Python
A class represents a collection of objects that share similar attributes. It serves as a framework or design from which individual objects are instantiated. It is an abstract concept and cannot exist in a physical form.
A class serves as a custom blueprint for generating objects. It outlines the attributes, properties, and actions associated with those objects.
Imagine a class as a blueprint for a structure. A structure encompasses all the specifics regarding its floors, rooms, doors, windows, and so forth. We have the capability to construct numerous structures utilizing these specifications. Therefore, the structure can be regarded as a class, and we are able to generate multiple instances of this class.
Syntax:
The following demonstrates the syntax for class definition in Python:
class ClassName:
# class attribute
Example: Creating a Class
Let's examine an example to understand how to define a Class in Python.
# define a class
class Car:
car_type = "Sedan" # Class attribute
Explanation
In this example, we have established a class referred to as Car. Within this class, the variable car_type = "Sedan" serves as a class attribute, which is collectively accessible to all instances created from this class.
Objects in Python
An object represents a tangible entity in the real world that possesses both state and behavior. It is an instantiation of a class. To put it differently, an object is a concrete item that can be perceived through touch, such as a vehicle or a piece of furniture, among other examples.
Syntax:
The following illustrates the syntax for creating an object in Python:
NameofObject = ClassName
Example: Creating an Object
Let's examine an example to illustrate how to create an Object in Python.
Example
class Car:
car_type = "Sedan"
# Create an object from the class
honda_city = Car()
# Access the class attribute
print(honda_city.car_type)
Output:
Explanation
In the preceding illustration, we established a Class referred to as Car, where car_type = "Sedan" serves as a class attribute that is collectively utilized by all instances of this class.
Relation Between Class and Objects
A class, in isolation, holds no significance until it is utilized to instantiate objects.
A Class specifies the characteristics and actions (methods) that an object will possess.
In this illustration, the Car is established as a Class, while Car 1, Car 2, and Car 3 are identified as the instances or objects. For instance, Car 1, Car 2, and Car 3 can represent models such as Honda City, Hyundai Creta, and others.
__init__ Function
The init function serves as a constructor in Python, which automatically sets the object's attributes upon the creation of a new instance derived from a class.
Syntax:
The structure for utilizing the init function in Python is illustrated as follows:
class ClassName:
def __init__(self, parameter1, parameter2, ...):
# Initializing instance variables
self.attribute1 = parameter1
self.attribute2 = parameter2
……………and more
Example: __init__ function
Let’s examine an illustration to understand the application of the init function in Python.
Example
class Car: # Class defined
car_type = "Sedan" # Class attribute
def __init__(self, car_name, engine): #__init__() function
self.car_name = car_name # Instance attribute
self.engine = engine # Instance attribute
car1 = Car("HondaCity", 250)
print(car1.car_name)
print(car1.engine)
Output:
HondaCity
250
Explanation
In the example provided, we utilized the init function to define parameters (car_name, engine) and associate them with instance attributes through the use of self.
The instance attributes self.car_name and self.Engine hold distinct information pertinent to each individual object.
The class Car includes an instance referred to as car1, which possesses the following attributes:
- car_name = "HondaCity"
- engine = 250
Self Parameter
In Python, the keyword self is utilized within class methods to denote the specific instance of the class. This allows for the retrieval of the methods and properties associated with that object.
Example: Self Parameter
Let’s examine an illustration of utilizing the self parameter to access the attributes and methods associated with an object.
Example
class Car:
def __init__(self, car_name, engine):
self.car_name = car_name
self.engine = engine
def run(self): #self parameter
print(f"{self.car_name} is running well")
# Creating an instance of Car
car1 = Car("HondaCity", 250)
car1.run()
Output:
Honda City is running well
Explanation
In the preceding example, we employed the init function to define parameters (car_name, engine) and allocate them to instance attributes by utilizing self.
The attributes self.car_name and self.engine are instance-specific properties that hold information, with the 'self' keyword enabling each individual object to retain its own unique data.
We utilized the self parameter. The self.car_name enables this method to reference the car's name linked to that particular instance.
__str__ Method
In Python, the str method enables us to create and specify a personalized string representation for an object.
Example: __str__ method
Let's examine a scenario in which we utilize the str method.
Example
class Car:
def __init__(self, car_name, kms_driven):
self.car_name = car_name
self.kms_driven = kms_driven
#__str__ method
def __str__(self):
return f"{self.car_name} is {self.kms_driven} Kilometres driven." #Returning a string
car1 = Car("Honda City", 45000)
car2 = Car("Swift Dzire", 15000)
print(car1)
print(car2)
Output:
Honda City has 45000 Kilometres driven.
Swift Dzire has 15000 Kilometers driven.
Explanation
As we have discovered, the str method enables us to create and specify a personalized string representation for an object.
The str method is invoked automatically whenever we utilize print or str(object). The return statement specifies what will be displayed when the object is printed.
Class and Instance Variables
In Python, variables can be categorized into two distinct types:
- Class Variables
- Instance Variables
These two variables are separate entities and are essential to grasp in order to gain insights into object-oriented programming.
Class Variables
Class variables refer to variables that are common to all instances of a given class. Every object created from that class has the ability to both access and alter these variables. The value of a class variable remains consistent across all objects unless it is specifically overridden in an individual object.
Instance Variables
In Python, instance variables are specific to each individual instance or object created from a class. Typically, the init method is employed to establish these instance variables. Each object retains its own copy of the instance variables, which operates independently from those of other objects.
Example
Let us examine an example to gain a clearer understanding of Instance Variables:
Example
class Car:
# Class variable
car_type = "Sedan"
def __init__(self, carname, kms_driven):
# Instance variables
self.carname = carname
self.kms_driven = kms_driven
# Create objects
car1 = Car("HondaCity", 12000)
car2 = Car("BMW", 1500)
# Access class and instance variables
print(car1.car_type) # (Class variable)
print(car1.carname) # (Instance variable)
print(car2.carname) # (Instance variable)
# Modify instance variables
car1.carname = "Alto"
print(car1.carname) # (Updated instance variable)
# Modify class variable
Car.car_type = "Hatchback"
print(car1.car_type) # (Updated class variable)
print(car2.car_type)
Output:
Sedan
HondaCity
BMW
Alto
Hatchback
Hatchback
Explanation
In the code presented above, we have thoroughly elucidated the concepts of Class variables and Instance variables.
Here we have created the objects:
car1 = Car("HondaCity", 12000)
car2 = Car("BMW", 1500)
In this section, we have gained access to both Class and Instance variables:
print(car1.car_type) # Output: Sedan
print(car1.carname) # Output: HondaCity
print(car2.carname) # Output: BMW
Subsequently, we made adjustments to the Class Variable and instance variable for all objects involved.
Benefits of Using Classes in Python
- Avoiding Code Repetition: Classes help us define common functionality that can be reused throughout the code, thereby helping us avoid writing the same piece of code multiple times.
- Keep Data and Behavior in a single entity: As we know, a Class determines the attributes and behavior of the objects, so we bundle all these functionalities together as it helps us to organize our code better.
- Solve Complex Problems: Classes can help us solve complex and real-world programming problems, as they enable us to avoid code repetition and keep all data in a single entity.
Conclusion
In object-oriented programming, the concepts of Classes and Objects are fundamental and intricately linked. A class serves as a customized template for generating objects, as it specifies the properties and functionalities associated with each object instance.
An object represents a specific instance of a class. For instance, consider the Car as a Class, while the Honda City and the Tata Nexon serve as the corresponding objects.
Python Classes and Objects FAQs
1. What is a Class in Python?
A class serves as a custom blueprint for generating objects. It specifies the attributes, properties, and actions associated with those objects.
2. What is an object in Python?
An object is referred to as an instantiation of a class. For instance, consider a class named CAR; the various objects derived from that class would include models such as Honda City, Creta, and others.
3. How do you create a class in Python?
The -Class- keyword serves the purpose of defining a Class in Python. As an illustration:
# define a class
class Car:
car_type = "Sedan" # Class attribute
4. What are attributes and methods?
Attributes refer to the variables that are established within a class, serving to store data pertinent to that class or its instantiated objects.
Methods are functions that are defined within a class and represent the behaviors or actions associated with an object.
5. What is _ _init_ _?
A constructor function is responsible for setting up the attributes of an object at the time of its instantiation.
6. What is self?
An identifier for the present object instance, utilized for accessing properties and functions.