02Jun
Build a Python Command-line Program Using OOP
Build a Python Command-line Program Using OOP

In this tutorial, we will look at how to build a python program users can make use of to record memorable events in their life using object oriented programming concepts in python.

This program can be operated by users via two interfaces: from the terminal or through graphical user interface such as kivy framework.

However in this article, we will look at how to build and run this python program from the terminal. We will focus on how to fuse this program with Kivy framework in our subsequent article.

However before we delve into this tutorial, let’s examine concepts in object-oriented programming such as classes, attributes, methods and objects. There are other concepts such as polymorphism, multiple inheritance; but we will not make use of them to build our command-line program.

Object-Oriented Programming

Object-Oriented Programming, otherwise known as OOP, allows python developers to model real-world entities such as an online shopping platforms as objects which have some data or attributes associated with them and can perform certain behaviors using python methods.

Objects are kinds of classes or instances of classes. Every or each object has the same set of attributes or characteristics assigned to it. However, values related to these attributes differ or are not the same.

Furthermore, objects are designed to interact with other objects via methods. Methods in object-oriented programming are similar to python functions.

These methods have access to attributes of objects and determine the behavior of these objects. For instance, let’s assume we want to create a diary book application for users to record every memorable events in their life.

This diary book application will require two classes namely; Diarybook class and Diary class to function well. The Diarybook will specify a set of attributes such as a list of diaries whilst the Diary class will also specify a set of attributes such as memo, tags, date created, and id.

For the Diarybook class, we will define a set of methods such as create_diary, show_diaries, and search_diary to make it possible for users to create diary, list diaries and search diary via a filter.

There is also another type of method in object-oriented programming known as a special method. Every special method in python OOP begins with a double underscore. There are many special method types in python.

For instance the def __init__ special method is responsible for initializing the attributes or characteristics of objects once objects are created.

Classes in Python

Classes in python object-oriented programming can be described basically as the superclass of all objects. Also, they serve as blueprints for objects to follow. Thus objects are instances or kinds of classes.

Every class is a subclass of the Object class in python. This object class is a base class and is different from objects or instances of classes.

The object class is the base class of every class we will define in our command-line program. This object class also have attributes and methods which is inherited by the Diarybook and Diary class in this tutorial.

In addition, classes also define methods which define the behavior of objects.

Attributes in Python

Objects or instances of classes in python have attributes also known as characteristics that define them. For instance, a Diary object may have characteristics such as datecreated, memo, and tags.

Although a class can provide the same set of attributes to objects, objects can assign different values to each attribute.

For example, in our Diarybook command-line program, an object can assign a different value to the memo attribute whilst another object can also assign a different value to the memo attribute as well.

Attributes of these objects or instances can be accessed using the dot notation in python.

Self keyword in Python

Finally the special method __init__() and every other method in python OOP must always come with a keyword known as the self parameter.

This self keyword refers to objects or instances of a class. In addition, you can access methods and attributes of objects or instances using the self keyword.

Although it is conventional to label it as self, you can choose to use any name such as my, mine or this in your python code.

Requirements:

You need the following to be able to partake in this tutorial:

  • Python version 3
  • A text editor such as Vim
  • Linux host such as Debian

Building the Diary Class

For our Python-based command-line program, we will build two classes each and assign a set of specific attributes to these classes.

Use the following command to create a directory to contain files for our command-line program :

mkdir pyproject

Navigate or change into the directory you just created via the command below:

cd pyproject

Inside the pyproject directory, create the following files using the touch command:

touch menu.py diarybook.py

Now let’s build the Diary class which will contain users’ diaries. The Dairy class will contain attributes such as memo, tags, creationtime, and id

Copy and paste the following code inside the diarybook.py file.

import datetime



#Store the next available id for all new diaries or recent ones

last_id = 0



class Diary:

   '''Represent a diary in the diarybook.'''



   def __init__(self, memo, tags=' '):

       '''Initialize a new diary with memo and tags. Creation date of new notes and id are automatically set'''



       self.memo = memo

       self.tags = tags

       self.creation_date = datetime.date.today()

       global last_id

       last_id +=1

       self.id = last_id  





   def match(self, filter):

        '''checks if the diary matches the filter text.



        Return true if it matches exactly, false if it does not match. 

        

        Filter is case-sensitive'''  

    

        return filter in self.memo or self.tags

Now save and close the diarybook.py file using your text editor of choice.

Before we move on to create the Diarybook class, let’s test the class Diary code to ensure it is working.

On the terminal, execute the command below to start the python interpreter as follows:

python

Then make use of the following command below to create instances of the Diary class:

from diarybook.py import Diary
d1 = Diary("How are you")
d1.id
d1.datecreated
d1.diary_filter("How")

First of all we created an instance of the Diary class and named it d1.

Next, we added a memo “How are you” to the Diary.

The next three commands revealed the instance id, date it was created and how we can use the filter method to match the text “how” with the memo we just entered.

Building the Diarybook class

In this section, we will build the Diarybook class which will contain a list of diaries belonging to users, allows users to create a new diary, list all diaries in the Diarybook as well as find a particular diary via the filter.

Inside diarybook.py file, copy and paste the following code:

class Diarybook:   

    '''Represent a collection of diaries'''

    

    def __init__(self):

        ''' Initialize diarybook with an empty list'''



        self.diaries = []





    def new_diary(self, memo, tags=''):

       ''' Creates a new diary in the diarybook '''



       self.diaries.append(Diary(memo, tags))







    def search_diary(self, filter):

      ''' searches all diary that match the filter '''



      return [ diary for diary in self.diaries if diary.match(filter)]



Save and close the diarybook.py file.

On the terminal, execute the command below to start the python interpreter:

python

Then type the following commands to create a new diary, list diaries in the Diarybook and find diaries using the filter:

from diarybook import Diarybook
c = Diarybook()
c.create_diary("Travel Tomorrow")
c.create_diary("Rolls Royce")
c.create_diary("West Burger")
c.diaries[1].id

As shown above, the Diarybook class is working correctly.

Building the CLI Interface

Now open the menu.py file you created earlier and paste the following code:

import sys



from diarybook import Diary, Diarybook



class Menu:

 ''' Displays a list of choices on the terminal for  the user to run '''



 def __init__(self):



      self.diarybook = Diarybook()



      self.choices = {

           "1" : self.show_diaries,

           "2" : self.add_diary,

           "3" : self.search_diaries,

           "4" : self.quit



        }







 def display_menu(self):

       print(""" 



             Notebook Menu  



             1. Show diaries

             2. Add diary

             3. Search diaries

             4. Quit program

             """)
 

 def run(self):

     ''' Display menu and respond to user choices '''



     while True:

           self.display_menu()

           choice = input("Enter an option: " )

           action = self.choices.get(choice)

           if action:

                action()

           else:

              print("{0} is not a valid choice".format(choice))





 def show_diaries(self, diaries=None):

     ''' Display all diaries in diarybook '''



     if not diaries:

        diaries = self.diarybook.diaries

     for diary in diaries:

       print("{0}".format(diary.memo))





 def add_diary(self):

     ''' Add a new diary in the diarybook '''



     memo = input("Enter a memo:         " )

     self.diarybook.new_diary(memo)

     print("Your note has been added")   


 def search_diaries(self):

     ''' Search for a specific diary in the diarybook using the match filter '''



     filter = input("Search for:  ")

     diaries = self.diarybook.search_diary(filter)

     self.show_diaries(diaries)


 def quit(self):

      ''' quit or terminate the program '''



      print("Thank you for using diarybook today")

      sys.exit(0)



if __name__ == "__main__":

    Menu().run()

Save and close the menu.py file.

Then type the following command on the terminal to run the program. You can choose any of the available options to try it out.

python3 menu.py

The full code for this tutorial is on Github. You can clone it, add more functions to it to upgrade its behavior.

In our next article, we will look at how to add a graphical user interface to this program using Kivy framework making use of another concept in OOP known as inheritance.

In this article, we studied how we can make use of basic python OOP concepts such as classes, attributes, and methods to build a simple python-based command-line program.

One Reply to “Build a Python Command-line Program Using OOP”

  1. This is an informative post. Got a lot of info and details from here. Thank you for sharing this and looking forward to reading more of your post.

Leave a Reply