π Python BasicsΒΆ
Args and KwargsΒΆ
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
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ΒΆ
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
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
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
Import moduleΒΆ
Try to import just function needed rather than entire module. Modules and functions can be imported with alias.
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
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
Note
```markdown
- Packages: NumPy, pandas, Matplotlib, etc
- Modules: os, sys, csv, json, importlib, re, math, intertools
```