Introduction
Classes and objects are fundamental concepts in object-oriented programming (OOP). A class is a blueprint for creating objects (instances), providing initial values for state (member variables or properties) and implementations of behavior (member functions or methods). An object is an instance of a class, containing real data that the class blueprint defines.
This tutorial will guide you through creating a Python program that defines a simple class and creates an object from that class.
Example:
- Class Name:
Car
- Attributes:
brand
,model
,year
- Method:
display_info
(prints the car’s information) - Program Output:
Car: Toyota Corolla, Year: 2020
Problem Statement
Create a Python program that:
- Defines a class named
Car
. - The class has attributes:
brand
,model
, andyear
. - The class has a method named
display_info
that prints the car’s information. - Creates an object of the class and calls the method to display the car’s details.
Solution Steps
- Define the Class: Use the
class
keyword to define a class namedCar
. - Add an Initialization Method: Define the
__init__
method to initialize the object’s attributes. - Add a Method: Define a method named
display_info
to print the car’s details. - Create an Object: Instantiate an object of the
Car
class by passing appropriate arguments. - Call the Method: Call the
display_info
method on the object to display the car’s details.
Python Program
# Python Program to Define a Class and Create an Object
# Author: https://www.rameshfadatare.com/
# Step 1: Define the class
class Car:
# Step 2: Define the initialization method
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
# Step 3: Define a method to display car information
def display_info(self):
print(f"Car: {self.brand} {self.model}, Year: {self.year}")
# Step 4: Create an object of the Car class
my_car = Car("Toyota", "Corolla", 2020)
# Step 5: Call the method to display car details
my_car.display_info()
Explanation
Step 1: Define the Class
- The
Car
class is defined using theclass
keyword. The class serves as a blueprint for creating car objects.
Step 2: Add an Initialization Method
- The
__init__
method is a special method in Python classes that initializes new objects. It is called automatically when a new object is created. - The
__init__
method takesself
(which refers to the current object) and other parameters (brand
,model
,year
) to initialize the object’s attributes.
Step 3: Add a Method
- The
display_info
method is defined to print the car’s details. This method takesself
as a parameter, allowing it to access the object’s attributes.
Step 4: Create an Object
- An object
my_car
is created by calling theCar
class with specific arguments forbrand
,model
, andyear
. This invokes the__init__
method to initialize the object’s attributes.
Step 5: Call the Method
- The
display_info
method is called on themy_car
object to print the car’s details.
Output Example
Example Output:
Car: Toyota Corolla, Year: 2020
Additional Examples
Example 1: Define a Class with Multiple Methods
# Defining a class with multiple methods
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
def display_info(self):
print(f"Student: {self.name}, Age: {self.age}, Grade: {self.grade}")
def is_pass(self):
return self.grade >= 50
# Creating an object of the Student class
student = Student("Alice", 20, 85)
# Calling methods on the object
student.display_info()
print(f"Has passed: {student.is_pass()}")
Output:
Student: Alice, Age: 20, Grade: 85
Has passed: True
Example 2: Define a Class with Default Attribute Values
# Defining a class with default attribute values
class Book:
def __init__(self, title, author, pages=100):
self.title = title
self.author = author
self.pages = pages
def display_info(self):
print(f"Book: {self.title} by {self.author}, Pages: {self.pages}")
# Creating an object with default pages value
book1 = Book("1984", "George Orwell")
# Creating an object with custom pages value
book2 = Book("The Catcher in the Rye", "J.D. Salinger", 214)
# Displaying information about the books
book1.display_info()
book2.display_info()
Output:
Book: 1984 by George Orwell, Pages: 100
Book: The Catcher in the Rye by J.D. Salinger, Pages: 214
Example 3: Modify Object Attributes
# Modifying object attributes after creation
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def display_info(self):
print(f"Dog: {self.name}, Breed: {self.breed}")
# Creating an object of the Dog class
dog = Dog("Buddy", "Golden Retriever")
# Displaying initial information
dog.display_info()
# Modifying the object's attributes
dog.name = "Max"
dog.breed = "Labrador Retriever"
# Displaying modified information
dog.display_info()
Output:
Dog: Buddy, Breed: Golden Retriever
Dog: Max, Breed: Labrador Retriever
Conclusion
This Python program demonstrates how to define a class, create an object, and interact with it using methods. Classes and objects are essential components of object-oriented programming, providing a way to structure code and create reusable components. Understanding how to define and use classes is crucial for writing organized, maintainable, and scalable Python programs.