Skip to content

🐍 Python Basics¢

Args and KwargsΒΆ

Python
def sum_of(*args):
    sum = 0
    for x in args:
        sum += x
    return sum

print(sum_of(4, 5, 6))
Python
def sum_of(**kwargs):
    sum = 0
    for key, value in kwargs.items():
        sum += value
    return round(sum)

print(sum_of(coffee=2.99, cake=4.55, juice=2.99))

Scope: LEGB - Local, Enclosing, Global, Built-inΒΆ

Tuples are immutalbe while lists are mutable

Instantiate a custom Object

Python
class Recipe():
    def __init__(self, dish, items, time) -> None:
        self.dish = dish
        self.items = items
        self.time = time

    def contents(self):
        print(f"{self.dish} {str(self.items)} {str(self.time)}")


pizza = Recipe("Pizza", ["cheese", "bread", "tomato"], 45)
print(pizza.contents())

InheritanceΒΆ

Python
class Employees:
    def __init__(self, name, last) -> None:
        self.name = name
        self.last = last

class Supervisors(Employees):
    def __init__(self, name, last, password) -> None:
        super().__init__(name, last)
        self.password = password

class Chefs(Employees):
    def leave_request(self, days):
        return f"Return in {days} days"


adrian = Supervisors("Adrian", "A", "apple")
emily = Chefs("Emily", "E")
juno = Chefs("Juno", "J")

print(adrian.password)
print(emily.leave_request(20))
print(emily.name)
print(juno.name)

Abstract calsses and methodsΒΆ

  • Interoperability
  • Consistency
  • Code duplication
Python
from abc import ABC, abstractmethod


class Employee(ABC):
    @abstractmethod
    def donate(self):
        pass

class Donation(Employee):
    def donate(self):
        a = input("How much would you like to donate: ")
        return a

amounts = []
john = Donation()
j = john.donate()
amounts.append(j)

peter = Donation()
p = peter.donate()
amounts.append(p)

print(amounts)

Method Resolution Order (MRO)ΒΆ

MRO determines the order in which a given method or attribute passed is searched or it's resloution. Method resultion default order is bottom -> top and left -> right

  • Simple Inheritance
  • Multiple Inheritance
  • Multi Level Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Beyond Python3 C3 Linearization algorithm - Adheres to Monotonicity - Follows Inheritance graph - Visits super class after local classes

Python
class A:
    num = 5

class B(A):
    num = 9

class C(B):
    pass

print(C.mro())
print(help(C))

ModulesΒΆ

Module generally imported in global scope but can be imported only for funciton scope.

  • Scope : Modules create a seperate namespace
  • Reusability : Avoid duplication
  • Simplicity : Helps avoid interdependency among modules

Types of modules: - Built-in (Eg, import math)

Any file can be module and here is the lookup by interpreter 1. Current Directory path 2. Build-in module directory 3. PYTHONPATH 4. Installation dependent default directory

Python
import sys

locations = sys.path
for path in locations:
    print(path) 

Import moduleΒΆ

Python
import sys

sys.path.insert(1, r'/app/yahoo')

Try to import just function needed rather than entire module. Modules and functions can be imported with alias.

Python
from math import sqrt

root = sqrt(9)

All function from the module can be explicitly imported with * (Eg. from math import *). But it's a bad practice to load everything.

Namespacing and scopingΒΆ

LEGB rule: Local -> Enclosed, Global, Built-in

It is discouraged to used global variables

  • Global: Access global variable from function
  • Non-Local : Special scope nested funtions defined previously
Python
def d():
    animal = "elephant"
    def e():
        nonlocal animal
        animal = "giraffe"
        print(f"insided nested functions: {animal}")

    print(f"before calling functions: {animal}")
    e()
    print(f"after calling functions: {animal}")

animal = "camel"
d()
print(f"global animal: {animal}")

Reload functionΒΆ

reload() - Reloads an imported module in Python. It can be used to detect dynamic change in the module without reruning the application

Python
import importlib

importlib.reload("module_name")