Monday, January 25, 2021

Python - Object Oriented Programming (Day 16)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Procedural Programming



Program works from top to bottom and jump into a function if needed.

Procedural Programming may be the first programming paradigm that a new developer will learn. Fundamentally, the procedural code is the one that directly instructs a device on how to finish a task in logical steps. (Refer to this Article)

When program get bigger and bigger, it will become complex since a function will lead to another function, and so on. The relationship between functions will be super complicated, and it is hard to memorize and maintain not only by the developers who take over this task, but also by the owner who built this program.


Object Oriented Programming



According to 'Procedural Programming', if we can break the functionalities into modules, then the complexity will reduce. Also, each module is reusable. You even don't need to understand the detail implementation of each modules. You just need to know how to use those modules.

For example, if we can split the process of building the self-driving car into some components such as camera, land detection, navigation, battery control, then the whole team (total 100 persons) can be split into four teams (20 persons per team) to take care of each parts simultaneously.  Also, once the navigation functionality from the self-driving car is done. Then we can easily migrate it to other projects such as drone.

It is the same concept such as "You are a manager of an restaurant". You don't need to tell Chef how to cook because Chef already have this skill. And you just need to let Chef know when to cook.


Class and Object



In OOP, we try to model real-life objects, and those objects have things and can do things (blueprint).

The things they have are their attributes.
The things they can do are called methods.

For example, we can model a waiter as the following sample code.
class Waiter:
    # has (Attributes)
    is_holding_plate = True
    table_responsible = [1, 2, 3]

    # does (Methods)
    def take_order(table, order):
        print(f"taking order {order} for table {table}")

    def take_payment(amount):
        print(f"take payment {amount}")


Once we have defined this, then we can have multiple objects generated from this blueprint.
In OOP, we call this blueprint a Class.

Ex: 
# Waiter is a class
# waiter_john and waiter_jake are objects
waiter_john = Waiter()
waiter_jake = Waiter()



Turtle Graphic



We will use Turtle Graphic to learn how to construct objects and accessing attributes and methods.

Ex:

from turtle import Turtle, Screen

# Construct Object
my_turtle = Turtle()
print(my_turtle)

# Accessing Attributes
my_screen = Screen()
print(my_screen.canvheight)

# Access Methods
my_turtle.shape("turtle")



How to add a Python Packages to our project?



For example, if we want to use prettytable package in our project, how do we install it?

1. Go to Python Package Index website


2. Search 'prettytable' and select the first one


3. Run the following command


python -m pip install -U prettytable


4. Read 'prettytable' document to understand how to use this package.

Ex:

from prettytable import PrettyTable

x = PrettyTable()
x.field_names = ["Column 1", "Column 2"]
x.add_row(["Demo 1", 123])
x.add_row(["Demo 2", 4565])
print(x)

Result:

+----------+----------+
| Column 1 | Column 2 | +----------+----------+ | Demo 1 | 123 | | Demo 2 | 4565 | +----------+----------+



Challenge - Coffee Machine (Revise the day 15 challenge to OOP style)



Build a Coffee Machine Program which support some functionalities below:
    * Prompt user by asking “What would you like? (espresso/latte/cappuccino):
    * Turn off the Coffee Machine by entering “off” to the prompt
    * Print report.
    * Check resources sufficient?
    * Process coins
    * Check transaction successful?
    * Make Coffee.

Ex: 
from menu import Menu
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine

menu = Menu()
coffee_maker = CoffeeMaker()
money_machine = MoneyMachine()

is_machine_on = True

while is_machine_on:
    user_select = input(f"What would you like? { menu.get_items()}:")

    if user_select == "report":
        coffee_maker.report()
        money_machine.report()
    elif user_select == "off":
        is_machine_on = False
    else:
        drink = menu.find_drink(user_select)

        if drink is None:
            print("Invalid Input")
        else:
            if coffee_maker.is_resource_sufficient(drink):
                if money_machine.make_payment(drink.cost):
                    coffee_maker.make_coffee(drink)


No comments:

Post a Comment