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
- 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.
- The class also has three methods: get_title, get_author, and get_pages.
- The get_title method returns the title of the book.
- The get_author method returns the author of the book.
- The get_pages method returns the number of pages in the book.
- 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.
- The get_title method is called on the book object to retrieve the title of the book, which is then printed.
- The get_author method is called on the book object to retrieve the author of the book, which is then printed.
- The get_pages method is called on the book object to retrieve the number of pages in the book, which is then printed.
- 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 EBook that inherits from the Book class.
Create a Python class called ShoppingCart with attributes items and total_cost.
Create a Python class called Animal with attributes name and color.
Create a Python class called Dog that inherits from the Animal class.
Python oops program to create a class with the constructor.
Python oops program to create a class with an instance variable.