Welcome to day 2:
File my_module.py
:
1module_name = "my_module"
2
3def my_fancy_function():
4 print("this is fancy")
5
6class MyClass:
7 def __init__(self):
8 print("Congrats: You initialized a very cool object")
File main.py
:
1from my_module import MyClass as MyAlias
2import my_module.my_fancy_function
3
4mc = MyAlias()
5my_module.my_fancy_function()
import
as
import numpy as np
math
the math libsys
info about your python systemos
to deal with OS related things e.g. pathsUse the python standard modules sys, os, math
to:
\[ \sin^2 (\pi / 3), \left ( \begin{matrix} 10 \\ 5 \end{matrix} \right ) \]
__init__.py
file that marks the directory as a packageA package "parent" containing three sub-packages:
1parent/
2 __init__.py
3 parent.py
4 one/
5 __init__.py
6 one.py
7 two/
8 __init__.py
9 two.py
10 three.py
Now you can import like:
1from parent.one.one import one_function
2import parent.three
3import parent.two.two as ptwo
for elem in [1,2,3]
)https://peps.python.org/pep-3128/#motivation
Possibility 1: [list].sort()
reverse=True
for descendingNone
key=
Possibility 2: Python builtin sorted
reverse=
and key=
How to sort these?:
(x, y)
by x
or y
or x*y
list of lists according to 3rd element:
[[_, _, <sort_by_this>], [_, _, <sort_by_this>] ...]
The key is the key
named parameter
Examples:
1arr = [-2.4, 3.8, 1.2, 0.0]
2arr.sort(key=abs)
3>>> [0.0, 1.2, -2.4, 3.8]
4
5from operator import itemgetter as getit
6arr = [(0,2), (1,4), (2,-3), (-3, 0)]
7print(sorted(arr, key=getit(1)))
8>>> [(2, -3), (-3, 0), (0, 2), (1, 4)]
• iterables
can be enumerated using enumerate(iterable)
• useful if we are actually also interested in the indices apart from values
1list(enumerate(["zero", "one", "two"]))
2>>> [(0, 'zero'), (1, 'one'), (2, 'two')]
3
4for (idx, elem) in list(enumerate(["zero", "one", "two"])):
5 print("{}: {}".format(idx, elem))
6>>> 0: zero
7>>> 1: one
8>>> 2: two
operator.itemgetter
1>>> help(operator.itemgetter)
2Help on class itemgetter in module operator:
3
4class itemgetter(builtins.object)
5 | itemgetter(item, ...) --> itemgetter object
6 |
7 | Return a callable object that fetches the given item(s) from its operand.
8 | After f = itemgetter(2), the call f(r) returns r[2].
9 | After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
10 ...
Frequent Tasks involving lists:
• Ad hoc small list to iterate over
• Contitional subset of a larger list
Use List Compehension:
As filter:
1newlist = [expression for item in iterable if condition == True]
As manipulator:
1newlist = [expression(item) if condition(item) else other_expression(item) for item in iterable]
1# fruits that contain an 'a' character
2fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
3newlist = []
4
5for x in fruits:
6 if "a" in x:
7 newlist.append(x)
8
9# with list comprehension this becomes:
10newlist = [f for f in fruits if 'a' in f]
string.ascii_letters
and random.randint
)More to loop control: Stopping in the middle
Single Loop:
break
: step out of current loop and stop loopingcontinue
: step out of current loop step but continue the loopNested Loop:
--break--
to go back to outer loopExamples:
1# basic example using break
2for i in range(5):
3 if i == 3:
4 break
5 print(i, end=" ")
6
7# basic example using continue
8for i in range(5):
9 if i == 3:
10 continue
11 print(i, end=" ")
if-else clause, generic example:
1if <some condition>:
2 print("some condition is TRUE")
3 break # we might break here if conditions are mutual exclusive
4elif <other condition>:
5 print("another condition is TRUE")
6elif <yet another condition>:
7 print("yet another condition is TRUE")
8else:
9 print("Everything above has evaluated to FALSE")
can be used to emulate a select
-case
type of behaviour known from other languages
6
:
matrix3d = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
. Write a function for doing so which returns the value
and stops the iteration when found.6
Behavior and functionality is separated between parent (base) and child class
Implicitly a class inherits for Python's object
cf. <YourClass>.__bases__
1class Vehicle:
2 def __init__(self):
3 self._capacity = None
4 self._num_passengers = None
5
6 def is_full(self):
7 if self._num_passengers == self._capacity:
8 return True
9 else:
10 return False
11
12class Car(Vehicle):
13 def __init__(self):
14 super(Car, self).__init__() # cf. in a second ...
15 self._capacity = 5
1class Car(Vehicle):
2 ...
3 def make_sound(self):
4 print("wrooom")
5
6
7class Bus(Vehicle):
8 ...
9 def make_sound(self):
10 print("ROOAAAARRRR")
11
12
13class ElectricCar(Car):
14 ...
15 def make_sound(self):
16 print("zzzzzzzzz")
super
super(ClassName, self).__init__()
• as in other languages there is the concept of privacy
• private attributes / methods are not passed to child classes
• this is done by starting class member names with a double underscore (__
)
• trying to access these from child class code will raise a AttributeError
1class A:
2 def __private_method(self):
3 print("private method called")
4
5class B(A):
6 def get_name(self):
7 self.__private_method()
8 print("get_name called")
9
10b1 = B()
11b1.get_name()
12>>> AttributeError: 'B' object has no attribute '_B__private_method'
Table of Contents | t |
---|---|
Exposé | ESC |
Presenter View | p |
Source Files | s |
Slide Numbers | n |
Toggle screen blanking | b |
Show/hide next slide | c |
Notes | 2 |
Help | h |