What is OOP programming
- Stands for object oriented programming
- Instead of being more focussed on functions and procedural abstraction this is more focussed on objects
- An object is an data type which uses something called inheritance
- 4 basics include: abstraction, encapsulation, inheritance and polymorphism
Here is a code snippet from online showcasing OOP
Data Structures Projects
Tri 3 TT1 Data Structures
Week 2
Replit
Menu.py
self
self
as it suggests, refers to itself- the object which has called the method. That is, if you have N objects calling the method, then self.a
will refer to a separate instance of the variable for each of the N objects. Imagine N copies of the variable a
for each object
init
__init__
is what is called as a constructor in other OOP languages such as C++/Java. The basic idea is that it is a special method which is automatically called when an object of that Class is created
class Example
class receipt():
def __init__(self,apples,figs,dates):
self.apples = apples
self.figs = figs
self.dates = dates
self.bill = apples + figs + dates
print ("Buy",self.apples,"apples", self.figs,"figs
and",self.dates,"dates.
Total bill is",self.receipt," pieces of fruit")
purchase = receipt(5,6,7)
result
> Buy 5 apples 6 figs and 7 dates. Total fruitty bill is 18 pieces of fruit
Replit Week 1
Week 1
Python Lists Vs Dictionaries
- List is a collection of index values pairs as that of array in JS. Dictionary is a hashed structure of key and value pairs.
InfoDB Lists
KVDb = []
# List with dictionary records placed in a list
KVDb.append({
"FirstName": "Karthik",
"LastName": "Valluri",
"DOB": "July 22",
"Location": "San Diego",
"Personal Email": "karthikv722@gmail.com",
"School Email": "karthikv44293@stu.powayusd.com",
"Coding_Languages":["Python","JS","CSS","HTML", "Java"]
})
Print the second car from Mort’s Owns_Cars list
x = InfoDb[0]["Coding_Languages"][1]
result: JS
There is also a method called get() on the Dictionary(InfoDb[0]) that will give you the same result:
x = InfoDb[0].get("Coding_Languages")[2]
result: CSS
Print Content from InfoDB
# given an index this will print InfoDb content
def print_data(n):
print(InfoDb[n]["FirstName"], InfoDb[n]["LastName"]) # using comma puts space between values
print("\t", "Cars: ", end="") # \t is a tab indent, end="" make sure no return occurs
print(", ".join(InfoDb[n]["Owns_Cars"])) # join allows printing a string list with separator
print()
def tester():
print("For loop")
for_loop()
print("While loop")
while_loop(0) # requires initial index to start while
print("Recursive loop")
recursive_loop(0) # requires initial index to start recursion
While Loop
# while loop contains an initial n and an index incrementing statement (n += 1)
def while_loop(n):
while n < len(InfoDb):
print_data(n)
n += 1
return
For Loop
# for loop iterates on length of InfoDb
def for_loop():
for n in range(len(InfoDb)):
print_data(n)
Tri 3 TT0 Python Menu, Replit, Github
Python Menu w/ data structures and try/except statements
# menu.py - function style menu
# Imports typically listed at top
# each import enables us to use logic that has been abstracted to other files and folders
import loopy
import mathpy
import funcy
import patterns
# Main list of [Prompts, Actions]
# Two styles are supported to execute abstracted logic
# 1. file names will be run by exec(open("filename.py").read())
# 2. function references will be executed directly file.function()
main_menu = [
["Stringy", "stringy.py"],
["Listy", "listy.py"],
["Loopy", loopy.main],
]
# Submenu list of [Prompt, Action]
# Works similarly to main_menu
sub_menu = [
["Factors", mathpy.factors],
["GCD", mathpy.gcd],
["LCM", mathpy.lcm],
["Primes", mathpy.primes],
]
patterns_sub_menu = [
["Patterns", "patterns.py"],
["PreFuncy", "prefuncy.py"],
["Funcy", funcy.ship],
]
# Menu banner is typically defined by menu owner
border = "=" * 25
banner = f"\n{border}\nPlease Select An Option\n{border}"
# def menu
# using main_menu list:
# 1. main menu and submenu reference are created [Prompts, Actions]
# 2. menu_list is sent as parameter to menuy.menu function that has logic for menu control
def menu():
title = "Function Menu" + banner
menu_list = main_menu.copy()
menu_list.append(["Math", submenu])
menu_list.append(["Patterns", patterns_submenu])
buildMenu(title, menu_list)
# def submenu
# using sub menu list above:
# sub_menu works similarly to menu()
def submenu():
title = "Function Submenu" + banner
buildMenu(title, sub_menu)
def patterns_submenu():
title = "Function Submenu" + banner
buildMenu(title, patterns_sub_menu)
def buildMenu(banner, options):
# header for menu
print(banner)
# build a dictionary from options
prompts = {0: ["Exit", None]}
for op in options:
index = len(prompts)
prompts[index] = op
# print menu or dictionary
for key, value in prompts.items():
print(key, '->', value[0])
# get user choice
choice = input("Type your choice> ")
# validate choice and run
# execute selection
# convert to number
try:
choice = int(choice)
if choice == 0:
# stop
return
try:
# try as function
action = prompts.get(choice)[1]
action()
except TypeError:
try: # try as playground style
exec(open(action).read())
except FileNotFoundError:
print(f"File not found!: {action}")
# end function try
# end prompts try
except ValueError:
# not a number error
print(f"Not a number: {choice}")
except UnboundLocalError:
# traps all other errors
print(f"Invalid choice: {choice}")
# end validation try
buildMenu(banner, options) # recursion, start menu over again
if __name__ == "__main__":
menu()
Python Menu (Ship Pattern)
#funcy.py
import time
# terminal print commands
ANSI_CLEAR_SCREEN = u"\u001B[2J"
ANSI_HOME_CURSOR = u"\u001B[0;0H\u001B[2"
OCEAN_COLOR = u"\u001B[44m\u001B[2D"
SHIP_COLOR = u"\u001B[32m\u001B[2D"
RESET_COLOR = u"\u001B[0m\u001B[2D"
def ocean_print():
# print ocean
print(ANSI_CLEAR_SCREEN, ANSI_HOME_CURSOR)
print("\n\n\n\n")
print(OCEAN_COLOR + " " * 35)
# print ship with colors and leading spaces
def ship_print(position):
print(ANSI_HOME_CURSOR)
print(RESET_COLOR)
sp = " " * position
print(sp + " |\ ")
print(sp + " |/ ")
print(SHIP_COLOR, end="")
print(sp + "\__ |__/ ")
print(sp + " \____/ ")
print(RESET_COLOR)
# ship function, iterface into this file
def ship():
# only need to print ocean once
ocean_print()
# loop control variables
start = 0 # start at zero
distance = 60 # how many times to repeat
step = 2 # count by 2
# loop purpose is to animate ship sailing
for position in range(start, distance, step):
ship_print(position) # call to function with parameter
time.sleep(.1)
Github Links
https://github.com/kar722/CSPTri3/blob/main/week0/menu.py