Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    JavaScript

    Introduction to Web Components. Part 1: Native vs Virtual DOM

    Express.js

    Securing Node.js Applications with JWT and Passport.js

    Flask

    Implementing a BackgroundRunner with Flask-Executor

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Thursday, September 18
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Python / Build a Python Command-line Program Using OOP
    Python

    Build a Python Command-line Program Using OOP

    Michael K.By Michael K.June 2, 2020No Comments8 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Build a Python Command-line Program Using OOP
    Build a Python Command-line Program Using OOP. Thumbnail
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    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.

    Read More:  Python Array Explained and Visualized

    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.

    Read More:  How To Secure Python Web App Using Bandit

    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.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Michael K.

      Related Posts

      Flask Development Made Easy: A Comprehensive Guide to Test-Driven Development

      January 4, 2024

      Creating Our Own Chat GPT

      July 27, 2023

      The Ultimate Guide to Pip

      June 12, 2023
      Leave A Reply Cancel Reply

      You must be logged in to post a comment.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      B2B Leads November 25, 2024

      Leveraging Case Studies and Testimonials for B2B Leads

      Utilizing case studies and testimonials can significantly enhance your B2B lead generation efforts. These powerful tools showcase real success stories, build credibility, and demonstrate how your products solve specific challenges, ultimately attracting more clients.

      Style like a pro with CSS variables

      May 12, 2023

      Programming Patterns. Strategy, Observer, Iterator

      February 8, 2017

      MSP Marketing Made Easy: 7 Proven Automation Tools

      May 3, 2025

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      Strategies to Cultivate Creativity and Innovation in Startups

      Startups December 5, 2024

      Working With API in React Application using Axios and Fetch

      JavaScript October 7, 2020

      How To Secure Python Web App Using Bandit

      Programming February 13, 2021

      Strategic Methods for Building a LinkedIn Prospect List

      LinkedIn December 10, 2024

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      Programming

      23. Node.js Lessons. Domains, asynchronous try.. catch. Part 2.

      Wiki

      Поиск заказа на UpWork

      JavaScript

      React Lesson 10: Normalize Data with Immutable.js

      Most Popular

      Setting Up Automated Semantic Versioning For Your NodeJS Project

      JavaScript

      Interview With Oleg

      Interview

      Partnerships with Conferences: Announcement for 2019-2020

      Events
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.