44. Problem to create a Python class example

In this Python oops program, we will create a Python class example. Python class called Book with attributes title, author, and pages.

Python class example

Steps to solve the program
  1. The Book class is defined with a constructor method __init__ that takes title, author, and pages as parameters and initializes the instance variables self.title, self.author, and self.pages with the provided values.
  2. The class also has three methods: get_title, get_author, and get_pages.
  3. The get_title method returns the title of the book.
  4. The get_author method returns the author of the book.
  5. The get_pages method returns the number of pages in the book.
  6. The code creates an object book of the Book class by calling its constructor and passing the title “Harry Potter”, author “J.K. Rowling”, and number of pages 300 as arguments.
  7. The get_title method is called on the book object to retrieve the title of the book, which is then printed.
  8. The get_author method is called on the book object to retrieve the author of the book, which is then printed.
  9. The get_pages method is called on the book object to retrieve the number of pages in the book, which is then printed.
  10. Thus, we have created a Python class example.
				
					class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages
    
    def get_title(self):
        return self.title
    
    def get_author(self):
        return self.author
    
    def get_pages(self):
        return self.pages

# Create an object of the Book class
book = Book("Harry Potter", "J.K. Rowling", 300)
print("Title:", book.get_title())
print("Author:", book.get_author())
print("Pages:", book.get_pages())
				
			

Output:

				
					Title: Harry Potter
Author: J.K. Rowling
Pages: 300
				
			

Related Articles

Create a Python class called Laptop with attributes brand, model, and storage.

Create a Python class called EBook that inherits from the Book class.

Leave a Comment