Python Programming Simplified: An Insider's Guide to Core Concepts

Python Programming Simplified: An Insider's Guide to Core Concepts

Python Comprehensive Cheat Sheet

1 Primitive Datatypes and Operators

# You have numbers

  • Example: 4 # => 4
  • Math is what you would expect
    • Example: 2 + 2 # => 2
    • Example: 8 - 2 # => 8
    • Example: 20 * 2 # => 20
    • Example: 46 / 6 # => 8.0
  • Integer division rounds down for both positive and negative numbers.
    • Example: 6 // 4 # => 2
    • Example: -6 // 4 # => -2
    • Example: 6.0 // 4.0 # => 2.0 # works on floats too
    • Example: -6.0 // 4.0 # => -2.0
  • The result of division is always a float
    • Example: 20.0 / 4 # => 4.4444444444444446
  • Modulo operation
    • Example: 8 % 4 # => 2
  • i % j have the same sign as j, unlike C
    • Example: -8 % 4 # => 2
  • Exponentiation (x**y, x to the yth power)
    • Example: 2**4 # => 8
  • Enforce precedence with parentheses
    • Example: 2 + 4 * 2 # => 8
    • Example: (2 + 4) * 2 # => 8
  • Boolean values are primitives (Note: the capitalization)
    • Example: True # => True
    • Example: False # => False
  • negate with not
    • Example: not True # => False
    • Example: not False # => True
  • Boolean Operators
  • Note “and” and “or” are case-sensitive
    • Example: True and False # => False
    • Example: False or True # => True
  • True and False are actually 1 and 0 but with different keywords
    • Example: True + True # => 2
    • Example: True * 8 # => 8
    • Example: False - 6 # => -6
  • Comparison operators look at the numerical value of True and False
    • Example: 0 == False # => True
    • Example: 2 > True # => True
    • Example: 2 == True # => False
    • Example: -6 != False # => True
  • None, 0, and empty strings/lists/dicts/tuples/sets all evaluate to False.
  • All other values are True
    • Example: bool(0) # => False
    • Example: bool("") # => False
    • Example: bool([]) # => False
    • Example: bool({}) # => False
    • Example: bool(()) # => False
    • Example: bool(set()) # => False
    • Example: bool(4) # => True
    • Example: bool(-6) # => True
  • Using boolean logical operators on ints casts them to booleans for evaluation,
  • but their non-cast value is returned. Don’t mix up with bool(ints) and bitwise
  • and/or (&,|)
    • Example: bool(0) # => False
    • Example: bool(2) # => True
    • Example: 0 and 2 # => 0
    • Example: bool(-6) # => True
    • Example: bool(2) # => True
    • Example: -6 or 0 # => -6
  • Equality is ==
    • Example: 2 == 2 # => True
    • Example: 2 == 2 # => False
  • Inequality is !=
    • Example: 2 != 2 # => False
    • Example: 2 != 2 # => True
  • More comparisons
    • Example: 2 < 20 # => True
    • Example: 2 > 20 # => False
    • Example: 2 <= 2 # => True
    • Example: 2 >= 2 # => True
  • Seeing whether a value is in a range
    • Example: 2 < 2 and 2 < 4 # => True
    • Example: 2 < 4 and 4 < 2 # => False
  • Chaining makes this look nicer
    • Example: 2 < 2 < 4 # => True
    • Example: 2 < 4 < 2 # => False
  • (is vs. ==) is checks if two variables refer to the same object, but == checks
  • if the objects pointed to have the same values.
    • Example: a = [2, 2, 4, 4] # Point a at a new list, [2, 2, 4, 4]
    • Example: b = a # Point b at what a is pointing to
    • Example: b is a # => True, a and b refer to the same object
    • Example: b == a # => True, a's and b's objects are equal
    • Example: b = [2, 2, 4, 4] # Point b at a new list, [2, 2, 4, 4]
    • Example: b is a # => False, a and b do not refer to the same object
    • Example: b == a # => True, a's and b's objects are equal
  • Strings are created with " or '
    • Example: "This is a string."
    • Example: 'This is also a string.'
  • Strings can be added too
    • Example: "Hello " + "world!" # => "Hello world!"
  • String literals (but not variables) can be concatenated without using ‘+’
    • Example: "Hello " "world!" # => "Hello world!"
  • A string can be treated like a list of characters
    • Example: "Hello world!"[0] # => 'H'
  • You can find the length of a string
    • Example: len("This is a string") # => 26
  • Since Python 3.6, you can use f-strings or formatted string literals.
    • Example: name = "Reiko"
    • Example: f"She said her name is {name}." # => "She said her name is Reiko"
  • Any valid Python expression inside these braces is returned to the string.
    • Example: f"{name} is {len(name)} characters long." # => "Reiko is 6 characters long."
  • None is an object
    • Example: None # => None
  • Don’t use the equality “==” symbol to compare objects to None
  • Use “is” instead. This checks for equality of object identity.
    • Example: "etc" is None # => False
    • Example: None is None # => True

2 Variables and Collections

# Python has a print function

  • Example: print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!
  • By default the print function also prints out a newline at the end.
  • Use the optional argument end to change the end string.
    • Example: print("Hello, World", end="!") # => Hello, World!
  • Simple way to get input data from console
    • Example: input_string_var = input("Enter some data: ") # Returns the data as a string
  • There are no declarations, only assignments.
  • Convention in naming variables is snake_case style
    • Example: some_var = 6
    • Example: some_var # => 6
  • Accessing a previously unassigned variable is an exception.
  • See Control Flow to learn more about exception handling.
    • Example: some_unknown_var # Raises a NameError
  • if can be used as an expression
  • Equivalent of C’s ‘?:’ ternary operator
    • Example: "yay!" if 0 > 2 else "nay!" # => "nay!"
  • Lists store sequences
    • Example: li = []
  • You can start with a prefilled list
    • Example: other_li = [4, 6, 6]
  • Add stuff to the end of a list with append
    • Example: li.append(2) # li is now [2]
    • Example: li.append(2) # li is now [2, 2]
    • Example: li.append(4) # li is now [2, 2, 4]
    • Example: li.append(4) # li is now [2, 2, 4, 4]
  • Remove from the end with pop
    • Example: li.pop() # => 4 and li is now [2, 2, 4]
  • Let’s put it back
    • Example: li.append(4) # li is now [2, 2, 4, 4] again.
  • Access a list like you would any array
    • Example: li[0] # => 2
  • Look at the last element
    • Example: li[-2] # => 4
  • Looking out of bounds is an IndexError
    • Example: li[4] # Raises an IndexError
  • You can look at ranges with slice syntax.
  • The start index is included, the end index is not
  • (It’s a closed/open range for you mathy types.)
    • Example: li[2:4] # Return list from index 2 to 4 => [2, 4]
    • Example: li[2:] # Return list starting from index 2 => [4, 4]
    • Example: li[:4] # Return list from beginning until index 4 => [2, 2, 4]
    • Example: li[::2] # Return list selecting elements with a step size of 2 => [2, 4]
    • Example: li[::-2] # Return list in reverse order => [4, 4, 2, 2]
  • Use any combination of these to make advanced slices
  • li[start:end:step]
  • Make a one layer deep copy using slices
    • Example: li2 = li[:] # => li2 = [2, 2, 4, 4] but (li2 is li) will result in false.
  • Remove arbitrary elements from a list with “del”
    • Example: del li[2] # li is now [2, 2, 4]
  • Remove first occurrence of a value
    • Example: li.remove(2) # li is now [2, 4]
    • Example: li.remove(2) # Raises a ValueError as 2 is not in the list
  • Insert an element at a specific index
    • Example: li.insert(2, 2) # li is now [2, 2, 4] again
  • Get the index of the first item found matching the argument
    • Example: li.index(2) # => 2
    • Example: li.index(4) # Raises a ValueError as 4 is not in the list
  • You can add lists
  • Note: values for li and for other_li are not modified.
    • Example: li + other_li # => [2, 2, 4, 4, 6, 6]
  • Concatenate lists with “extend()”
    • Example: li.extend(other_li) # Now li is [2, 2, 4, 4, 6, 6]
  • Check for existence in a list with “in”
    • Example: 2 in li # => True
  • Examine the length with “len()”
    • Example: len(li) # => 6
  • Tuples are like lists but are immutable.
    • Example: tup = (2, 2, 4)
    • Example: tup[0] # => 2
    • Example: tup[0] = 4 # Raises a TypeError
  • Note that a tuple of length one has to have a comma after the last element but
  • tuples of other lengths, even zero, do not.
    • Example: type((2)) # => <class 'int'>
    • Example: type((2,)) # => <class 'tuple'>
    • Example: type(()) # => <class 'tuple'>
  • You can do most of the list operations on tuples too
    • Example: len(tup) # => 4
    • Example: tup + (4, 6, 6) # => (2, 2, 4, 4, 6, 6)
    • Example: tup[:2] # => (2, 2)
    • Example: 2 in tup # => True
  • You can unpack tuples (or lists) into variables
    • Example: a, b, c = (2, 2, 4) # a is now 2, b is now 2 and c is now 4
  • You can also do extended unpacking
    • Example: a, *b, c = (2, 2, 4, 4) # a is now 2, b is now [2, 4] and c is now 4
  • Tuples are created by default if you leave out the parentheses
    • Example: d, e, f = 4, 6, 6 # tuple 4, 6, 6 is unpacked into variables d, e and f
  • respectively such that d = 4, e = 5 and f = 6
  • Now look how easy it is to swap two values
    • Example: e, d = d, e # d is now 6 and e is now 4
  • Dictionaries store mappings from keys to values
    • Example: empty_dict = {}
  • Here is a prefilled dictionary
    • Example: filled_dict = {"one": 2, "two": 2, "three": 4}
  • Note keys for dictionaries have to be immutable types. This is to ensure that
  • the key can be converted to a constant hash value for quick look-ups.
  • Immutable types include ints, floats, strings, tuples.
    • Example: invalid_dict = {[2,2,4]: "224"} # => Yield a TypeError: unhashable type: 'list'
    • Example: valid_dict = {(2,2,4):[2,2,4]} # Values can be of any type, however.
  • Look up values with []
    • Example: filled_dict["one"] # => 2
  • Get all keys as an iterable with “keys()”. We need to wrap the call in list()
  • to turn it into a list. We’ll talk about those later. Note - for Python
  • versions <3.7, dictionary key ordering is not guaranteed. Your results might
  • not match the example below exactly. However, as of Python 3.7, dictionary
  • items maintain the order at which they are inserted into the dictionary.
    • Example: list(filled_dict.keys()) # => ["three", "two", "one"] in Python <4.8
    • Example: list(filled_dict.keys()) # => ["one", "two", "three"] in Python 4.8+
  • Get all values as an iterable with “values()”. Once again we need to wrap it
  • in list() to get it out of the iterable. Note - Same as above regarding key
  • ordering.
    • Example: list(filled_dict.values()) # => [4, 2, 2] in Python <4.8
    • Example: list(filled_dict.values()) # => [2, 2, 4] in Python 4.8+
  • Check for existence of keys in a dictionary with “in”
    • Example: "one" in filled_dict # => True
    • Example: 2 in filled_dict # => False
  • Looking up a non-existing key is a KeyError
    • Example: filled_dict["four"] # KeyError
  • Use “get()” method to avoid the KeyError
    • Example: filled_dict.get("one") # => 2
    • Example: filled_dict.get("four") # => None
  • The get method supports a default argument when the value is missing
    • Example: filled_dict.get("one", 4) # => 2
    • Example: filled_dict.get("four", 4) # => 4
  • “setdefault()” inserts into a dictionary only if the given key isn’t present
    • Example: filled_dict.setdefault("five", 6) # filled_dict["five"] is set to 6
    • Example: filled_dict.setdefault("five", 6) # filled_dict["five"] is still 6
  • Adding to a dictionary
    • Example: filled_dict.update({"four":4}) # => {"one": 2, "two": 2, "three": 4, "four": 4}
    • Example: filled_dict["four"] = 4 # another way to add to dict
  • Remove keys from a dictionary with del
    • Example: del filled_dict["one"] # Removes the key "one" from filled dict
  • From Python 3.5 you can also use the additional unpacking options
    • Example: {'a': 2, **{'b': 2}} # => {'a': 2, 'b': 2}
    • Example: {'a': 2, **{'a': 2}} # => {'a': 2}
  • Sets store … well sets
    • Example: empty_set = set()
  • Initialize a set with a bunch of values.
    • Example: some_set = {2, 2, 2, 2, 4, 4} # some_set is now {2, 2, 4, 4}
  • Similar to keys of a dictionary, elements of a set have to be immutable.
    • Example: invalid_set = {[2], 2} # => Raises a TypeError: unhashable type: 'list'
    • Example: valid_set = {(2,), 2}
  • Add one more item to the set
    • Example: filled_set = some_set
    • Example: filled_set.add(6) # filled_set is now {2, 2, 4, 4, 6}
  • Sets do not have duplicate elements
    • Example: filled_set.add(6) # it remains as before {2, 2, 4, 4, 6}
  • Do set intersection with &
    • Example: other_set = {4, 4, 6, 6}
    • Example: filled_set & other_set # => {4, 4, 6}
  • Do set union with |
    • Example: filled_set | other_set # => {2, 2, 4, 4, 6, 6}
  • Do set difference with -
    • Example: {2, 2, 4, 4} - {2, 4, 6} # => {2, 4}
  • Do set symmetric difference with ^
    • Example: {2, 2, 4, 4} ^ {2, 4, 6} # => {2, 4, 6}
  • Check if set on the left is a superset of set on the right
    • Example: {2, 2} >= {2, 2, 4} # => False
  • Check if set on the left is a subset of set on the right
    • Example: {2, 2} <= {2, 2, 4} # => True
  • Check for existence in a set with in
    • Example: 2 in filled_set # => True
    • Example: 20 in filled_set # => False
  • Make a one layer deep copy
    • Example: filled_set = some_set.copy() # filled_set is {2, 2, 4, 4, 6}
    • Example: filled_set is some_set # => False

3 Control Flow and Iterables

# Let’s just make a variable

  • Example: some_var = 6
  • Here is an if statement. Indentation is significant in Python!
  • Convention is to use four spaces, not tabs.
  • This prints “some_var is smaller than 10”
    • Example: if some_var > 20:
    • Example: print("some_var is totally bigger than 20.")
    • Example: elif some_var < 20: # This elif clause is optional.
    • Example: print("some_var is smaller than 20.")
    • Example: else: # This is optional too.
    • Example: print("some_var is indeed 20.")
    • Example: For loops iterate over lists
    • Example: prints:
    • Example: dog is a mammal
    • Example: cat is a mammal
    • Example: mouse is a mammal
    • Example: for animal in ["dog", "cat", "mouse"]:
    • Example: # You can use format() to interpolate formatted strings
    • Example: print("{} is a mammal".format(animal))
    • Example: "range(number)" returns an iterable of numbers
    • Example: from zero up to (but excluding) the given number
    • Example: prints:
    • Example: 0
    • Example: 2
    • Example: 2
    • Example: 4
    • Example: for i in range(4):
    • Example: print(i)
    • Example: "range(lower, upper)" returns an iterable of numbers
    • Example: from the lower number to the upper number
    • Example: prints:
    • Example: 4
    • Example: 6
    • Example: 6
    • Example: 8
    • Example: for i in range(4, 8):
    • Example: print(i)
    • Example: "range(lower, upper, step)" returns an iterable of numbers
    • Example: from the lower number to the upper number, while incrementing
    • Example: by step. If step is not indicated, the default value is 2.
    • Example: prints:
    • Example: 4
    • Example: 6
    • Example: for i in range(4, 8, 2):
    • Example: print(i)
    • Example: Loop over a list to retrieve both the index and the value of each list item:
    • Example: 0 dog
    • Example: 2 cat
    • Example: 2 mouse
    • Example: animals = ["dog", "cat", "mouse"]
    • Example: for i, value in enumerate(animals):
    • Example: print(i, value)
    • Example: While loops go until a condition is no longer met.
    • Example: prints:
    • Example: 0
    • Example: 2
    • Example: 2
    • Example: 4
    • Example: x = 0
    • Example: while x < 4:
    • Example: print(x)
    • Example: x += 2 # Shorthand for x = x + 2
  • Handle exceptions with a try/except block
    • Example: try:
    • Example: # Use "raise" to raise an error
    • Example: raise IndexError("This is an index error")
    • Example: except IndexError as e:
    • Example: pass # Refrain from this, provide a recovery (next example).
    • Example: except (TypeError, NameError):
    • Example: pass # Multiple exceptions can be processed jointly.
    • Example: else: # Optional clause to the try/except block. Must follow
    • Example: # all except blocks.
    • Example: print("All good!") # Runs only if the code in try raises no exceptions
    • Example: finally: # Execute under all circumstances
    • Example: print("We can clean up resources here")
  • Instead of try/finally to cleanup resources you can use a with statement
    • Example: with open("myfile.txt") as f:
    • Example: for line in f:
    • Example: print(line)
  • Writing to a file
    • Example: contents = {"aa": 22, "bb": 22}
    • Example: with open("myfile2.txt", "w+") as file:
    • Example: file.write(str(contents)) # writes a string to a file
    • Example: import json
    • Example: with open("myfile2.txt", "w+") as file:
    • Example: file.write(json.dumps(contents)) # writes an object to a file
  • Reading from a file
    • Example: with open('myfile2.txt', "r+") as file:
    • Example: contents = file.read() # reads a string from a file
    • Example: print(contents)
  • print: {“aa”: 12, “bb”: 21}
    • Example: with open('myfile2.txt', "r+") as file:
    • Example: contents = json.load(file) # reads a json object from a file
    • Example: print(contents)
  • print: {“aa”: 12, “bb”: 21}
  • Python offers a fundamental abstraction called the Iterable.
  • An iterable is an object that can be treated as a sequence.
  • The object returned by the range function, is an iterable.
    • Example: filled_dict = {"one": 2, "two": 2, "three": 4}
    • Example: our_iterable = filled_dict.keys()
    • Example: print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object
    • Example: # that implements our Iterable interface.
  • We can loop over it.
    • Example: for i in our_iterable:
    • Example: print(i) # Prints one, two, three
  • However we cannot address elements by index.
    • Example: our_iterable[2] # Raises a TypeError
  • An iterable is an object that knows how to create an iterator.
    • Example: our_iterator = iter(our_iterable)
  • Our iterator is an object that can remember the state as we traverse through
  • it. We get the next object with “next()”.
    • Example: next(our_iterator) # => "one"
  • It maintains state as we iterate.
    • Example: next(our_iterator) # => "two"
    • Example: next(our_iterator) # => "three"
  • After the iterator has returned all of its data, it raises a
  • StopIteration exception
    • Example: next(our_iterator) # Raises StopIteration
  • We can also loop over it, in fact, “for” does this implicitly!
    • Example: our_iterator = iter(our_iterable)
    • Example: for i in our_iterator:
    • Example: print(i) # Prints one, two, three
  • You can grab all the elements of an iterable or iterator by call of list().
    • Example: list(our_iterable) # => Returns ["one", "two", "three"]
    • Example: list(our_iterator) # => Returns [] because state is saved

4 Functions

# Use “def” to create new functions

  • Example: def add(x, y):
  • Example: print("x is {} and y is {}".format(x, y))
  • Example: return x + y # Return values with a return statement
  • Calling functions with parameters
    • Example: add(6, 6) # => prints out "x is 6 and y is 6" and returns 22
  • Another way to call functions is with keyword arguments
    • Example: add(y=6, x=6) # Keyword arguments can arrive in any order.
  • You can define functions that take a variable number of
  • positional arguments
    • Example: def varargs(*args):
    • Example: return args
    • Example: varargs(2, 2, 4) # => (2, 2, 4)
  • You can define functions that take a variable number of
  • keyword arguments, as well
    • Example: def keyword_args(**kwargs):
    • Example: return kwargs
  • Let’s call it to see what happens
    • Example: keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
  • You can do both at once, if you like
    • Example: def all_the_args(*args, **kwargs):
    • Example: print(args)
    • Example: print(kwargs)
    • Example: all_the_args(2, 2, a=4, b=4) prints:
    • Example: (2, 2)
    • Example: {"a": 4, "b": 4}
  • When calling functions, you can do the opposite of args/kwargs!
  • Use * to expand args (tuples) and use ** to expand kwargs (dictionaries).
    • Example: args = (2, 2, 4, 4)
    • Example: kwargs = {"a": 4, "b": 4}
    • Example: all_the_args(*args) # equivalent: all_the_args(2, 2, 4, 4)
    • Example: all_the_args(**kwargs) # equivalent: all_the_args(a=4, b=4)
    • Example: all_the_args(*args, **kwargs) # equivalent: all_the_args(2, 2, 4, 4, a=4, b=4)
  • Returning multiple values (with tuple assignments)
    • Example: def swap(x, y):
    • Example: return y, x # Return multiple values as a tuple without the parenthesis.
    • Example: # (Note: parenthesis have been excluded but can be included)
    • Example: x = 2
    • Example: y = 2
    • Example: x, y = swap(x, y) # => x = 2, y = 2
  • (x, y) = swap(x,y) # Again the use of parenthesis is optional.
  • global scope
    • Example: x = 6
    • Example: def set_x(num):
    • Example: # local scope begins here
    • Example: # local var x not the same as global var x
    • Example: x = num # => 44
    • Example: print(x) # => 44
    • Example: def set_global_x(num):
    • Example: # global indicates that particular var lives in the global scope
    • Example: global x
    • Example: print(x) # => 6
    • Example: x = num # global var x is now set to 6
    • Example: print(x) # => 6
    • Example: set_x(44)
    • Example: set_global_x(6)
    • Example: prints:
    • Example: 44
    • Example: 6
    • Example: 6
  • Python has first class functions
    • Example: def create_adder(x):
    • Example: def adder(y):
    • Example: return x + y
    • Example: return adder
    • Example: add_20 = create_adder(20)
    • Example: add_20(4) # => 24
  • Closures in nested functions:
  • We can use the nonlocal keyword to work with variables in nested scope which shouldn’t be declared in the inner functions.
    • Example: def create_avg():
    • Example: total = 0
    • Example: count = 0
    • Example: def avg(n):
    • Example: nonlocal total, count
    • Example: total += n
    • Example: count += 2
    • Example: return total/count
    • Example: return avg
    • Example: avg = create_avg()
    • Example: avg(4) # => 4.0
    • Example: avg(6) # (4+6)/2 => 4.0
    • Example: avg(8) # (8+8)/4 => 6.0
  • There are also anonymous functions
    • Example: (lambda x: x > 2)(4) # => True
    • Example: (lambda x, y: x ** 2 + y ** 2)(2, 2) # => 6
  • There are built-in higher order functions
    • Example: list(map(add_20, [2, 2, 4])) # => [22, 22, 24]
    • Example: list(map(max, [2, 2, 4], [4, 2, 2])) # => [4, 2, 4]
    • Example: list(filter(lambda x: x > 6, [4, 4, 6, 6, 8])) # => [6, 8]
  • We can use list comprehensions for nice maps and filters
  • List comprehension stores the output as a list (which itself may be nested).
    • Example: [add_20(i) for i in [2, 2, 4]] # => [22, 22, 24]
    • Example: [x for x in [4, 4, 6, 6, 8] if x > 6] # => [6, 8]
  • You can construct set and dict comprehensions as well.
    • Example: {x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'}
    • Example: {x: x**2 for x in range(6)} # => {0: 0, 2: 2, 2: 4, 4: 9, 4: 26}

5 Modules

# You can import modules

  • Example: import math
  • Example: print(math.sqrt(26)) # => 4.0
  • You can get specific functions from a module
    • Example: from math import ceil, floor
    • Example: print(ceil(4.8)) # => 4
    • Example: print(floor(4.8)) # => 4
  • You can import all functions from a module.
  • Warning: this is not recommended
    • Example: from math import *
  • You can shorten module names
    • Example: import math as m
    • Example: math.sqrt(26) == m.sqrt(26) # => True
  • Python modules are just ordinary Python files. You
  • can write your own, and import them. The name of the
  • module is the same as the name of the file.
  • You can find out which functions and attributes
  • are defined in a module.
    • Example: import math
    • Example: dir(math)
  • If you have a Python script named math.py in the same
  • folder as your current script, the file math.py will
  • be loaded instead of the built-in Python module.
  • This happens because the local folder has priority
  • over Python’s built-in libraries.

6 Classes

# We use the “class” statement to create a class

  • Example: class Human:
  • Example: # A class attribute. It is shared by all instances of this class
  • Example: species = "H. sapiens"
  • Example: # Basic initializer, this is called when this class is instantiated.
  • Example: # Note that the double leading and trailing underscores denote objects
  • Example: # or attributes that are used by Python but that live in user-controlled
  • Example: # namespaces. Methods(or objects or attributes) like: __init__, __str__,
  • Example: # __repr__ etc. are called special methods (or sometimes called dunder
  • Example: # methods). You should not invent such names on your own.
  • Example: def __init__(self, name):
  • Example: # Assign the argument to the instance's name attribute
  • Example: self.name = name
  • Example: # Initialize property
  • Example: self._age = 0 # the leading underscore indicates the "age" property is
  • Example: # intended to be used internally
  • Example: # do not rely on this to be enforced: it's a hint to other devs
  • Example: # An instance method. All methods take "self" as the first argument
  • Example: def say(self, msg):
  • Example: print("{name}: {message}".format(name=self.name, message=msg))
  • Example: # Another instance method
  • Example: def sing(self):
  • Example: return 'yo... yo... microphone check... one two... one two...'
  • Example: # A class method is shared among all instances
  • Example: # They are called with the calling class as the first argument
  • Example: @classmethod
  • Example: def get_species(cls):
  • Example: return cls.species
  • Example: # A static method is called without a class or instance reference
  • Example: @staticmethod
  • Example: def grunt():
  • Example: return "*grunt*"
  • Example: # A property is just like a getter.
  • Example: # It turns the method age() into a read-only attribute of the same name.
  • Example: # There's no need to write trivial getters and setters in Python, though.
  • Example: @property
  • Example: def age(self):
  • Example: return self._age
  • Example: # This allows the property to be set
  • Example: @age.setter
  • Example: def age(self, age):
  • Example: self._age = age
  • Example: # This allows the property to be deleted
  • Example: @age.deleter
  • Example: def age(self):
  • Example: del self._age
  • When a Python interpreter reads a source file it executes all its code.
  • This name check makes sure this code block is only executed when this
  • module is the main program.
    • Example: if __name__ == '__main__':
    • Example: # Instantiate a class
    • Example: i = Human(name="Ian")
    • Example: i.say("hi") # "Ian: hi"
    • Example: j = Human("Joel")
    • Example: j.say("hello") # "Joel: hello"
    • Example: # i and j are instances of type Human; i.e., they are Human objects.
    • Example: # Call our class method
    • Example: i.say(i.get_species()) # "Ian: H. sapiens"
    • Example: # Change the shared attribute
    • Example: Human.species = "H. neanderthalensis"
    • Example: i.say(i.get_species()) # => "Ian: H. neanderthalensis"
    • Example: j.say(j.get_species()) # => "Joel: H. neanderthalensis"
    • Example: # Call the static method
    • Example: print(Human.grunt()) # => "*grunt*"
    • Example: # Static methods can be called by instances too
    • Example: print(i.grunt()) # => "*grunt*"
    • Example: # Update the property for this instance
    • Example: i.age = 42
    • Example: # Get the property
    • Example: i.say(i.age) # => "Ian: 42"
    • Example: j.say(j.age) # => "Joel: 0"
    • Example: # Delete the property
    • Example: del i.age
    • Example: # i.age # => this would raise an AttributeError

61 Inheritance

# Inheritance allows new child classes to be defined that inherit methods and

  • variables from their parent class.
  • Using the Human class defined above as the base or parent class, we can
  • define a child class, Superhero, which inherits the class variables like
  • “species”, “name”, and “age”, as well as methods, like “sing” and “grunt”
  • from the Human class, but can also have its own unique properties.
  • To take advantage of modularization by file you could place the classes above
  • in their own files, say, human.py
  • To import functions from other files use the following format
  • from “filename-without-extension” import “function-or-class”
    • Example: from human import Human
  • Specify the parent class(es) as parameters to the class definition
    • Example: class Superhero(Human):
    • Example: # If the child class should inherit all of the parent's definitions without
    • Example: # any modifications, you can just use the "pass" keyword (and nothing else)
    • Example: # but in this case it is commented out to allow for a unique child class:
    • Example: # pass
    • Example: # Child classes can override their parents' attributes
    • Example: species = 'Superhuman'
    • Example: # Children automatically inherit their parent class's constructor including
    • Example: # its arguments, but can also define additional arguments or definitions
    • Example: # and override its methods such as the class constructor.
    • Example: # This constructor inherits the "name" argument from the "Human" class and
    • Example: # adds the "superpower" and "movie" arguments:
    • Example: def __init__(self, name, movie=False,
    • Example: superpowers=["super strength", "bulletproofing"]):
    • Example: # add additional class attributes:
    • Example: self.fictional = True
    • Example: self.movie = movie
    • Example: # be aware of mutable default values, since defaults are shared
    • Example: self.superpowers = superpowers
    • Example: # The "super" function lets you access the parent class's methods
    • Example: # that are overridden by the child, in this case, the __init__ method.
    • Example: # This calls the parent class constructor:
    • Example: super().__init__(name)
    • Example: # override the sing method
    • Example: def sing(self):
    • Example: return 'Dun, dun, DUN!'
    • Example: # add an additional instance method
    • Example: def boast(self):
    • Example: for power in self.superpowers:
    • Example: print("I wield the power of {pow}!".format(pow=power))
    • Example: if __name__ == '__main__':
    • Example: sup = Superhero(name="Tick")
    • Example: # Instance type checks
    • Example: if isinstance(sup, Human):
    • Example: print('I am human')
    • Example: if type(sup) is Superhero:
    • Example: print('I am a superhero')
    • Example: # Get the "Method Resolution Order" used by both getattr() and super()
    • Example: # (the order in which classes are searched for an attribute or method)
    • Example: # This attribute is dynamic and can be updated
    • Example: print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
    • Example: # => <class 'human.Human'>, <class 'object'>)
    • Example: # Calls parent method but uses its own class attribute
    • Example: print(sup.get_species()) # => Superhuman
    • Example: # Calls overridden method
    • Example: print(sup.sing()) # => Dun, dun, DUN!
    • Example: # Calls method from Human
    • Example: sup.say('Spoon') # => Tick: Spoon
    • Example: # Call method that exists only in Superhero
    • Example: sup.boast() # => I wield the power of super strength!
    • Example: # => I wield the power of bulletproofing!
    • Example: # Inherited class attribute
    • Example: sup.age = 42
    • Example: print(sup.age) # => 42
    • Example: # Attribute that only exists within Superhero
    • Example: print('Am I Oscar eligible? ' + str(sup.movie))

62 Multiple Inheritance

# Another class definition

  • bat.py
    • Example: class Bat:
    • Example: species = 'Baty'
    • Example: def __init__(self, can_fly=True):
    • Example: self.fly = can_fly
    • Example: # This class also has a say method
    • Example: def say(self, msg):
    • Example: msg = '... ... ...'
    • Example: return msg
    • Example: # And its own method as well
    • Example: def sonar(self):
    • Example: return '))) ... ((('
    • Example: if __name__ == '__main__':
    • Example: b = Bat()
    • Example: print(b.say('hello'))
    • Example: print(b.fly)
  • And yet another class definition that inherits from Superhero and Bat
  • superhero.py
    • Example: from superhero import Superhero
    • Example: from bat import Bat
  • Define Batman as a child that inherits from both Superhero and Bat
    • Example: class Batman(Superhero, Bat):
    • Example: def __init__(self, *args, **kwargs):
    • Example: # Typically to inherit attributes you have to call super:
    • Example: # super(Batman, self).__init__(*args, **kwargs)
    • Example: # However we are dealing with multiple inheritance here, and super()
    • Example: # only works with the next base class in the MRO list.
    • Example: # So instead we explicitly call __init__ for all ancestors.
    • Example: # The use of *args and **kwargs allows for a clean way to pass
    • Example: # arguments, with each parent "peeling a layer of the onion".
    • Example: Superhero.__init__(self, 'anonymous', movie=True,
    • Example: superpowers=['Wealthy'], *args, **kwargs)
    • Example: Bat.__init__(self, *args, can_fly=False, **kwargs)
    • Example: # override the value for the name attribute
    • Example: self.name = 'Sad Affleck'
    • Example: def sing(self):
    • Example: return 'nan nan nan nan nan batman!'
    • Example: if __name__ == '__main__':
    • Example: sup = Batman()
    • Example: # The Method Resolution Order
    • Example: print(Batman.__mro__) # => (<class '__main__.Batman'>,
    • Example: # => <class 'superhero.Superhero'>,
    • Example: # => <class 'human.Human'>,
    • Example: # => <class 'bat.Bat'>, <class 'object'>)
    • Example: # Calls parent method but uses its own class attribute
    • Example: print(sup.get_species()) # => Superhuman
    • Example: # Calls overridden method
    • Example: print(sup.sing()) # => nan nan nan nan nan batman!
    • Example: # Calls method from Human, because inheritance order matters
    • Example: sup.say('I agree') # => Sad Affleck: I agree
    • Example: # Call method that exists only in 2nd ancestor
    • Example: print(sup.sonar()) # => ))) ... (((
    • Example: # Inherited class attribute
    • Example: sup.age = 200
    • Example: print(sup.age) # => 200
    • Example: # Inherited attribute from 2nd ancestor whose default value was overridden.
    • Example: print('Can I fly? ' + str(sup.fly)) # => Can I fly? False

7 Advanced

# Generators help you make lazy code

  • Example: def double_numbers(iterable):
  • Example: for i in iterable:
  • Example: yield i + i
  • Generators are memory-efficient because they only load the data needed to
  • process the next value in the iterable. This allows them to perform
  • operations on otherwise prohibitively large value ranges.
  • NOTE: range replaces xrange in Python 3.
    • Example: for i in double_numbers(range(2, 900000000)): # range is a generator.
    • Example: print(i)
    • Example: if i >= 40:
    • Example: break
  • Just as you can create a list comprehension, you can create generator
  • comprehensions as well.
    • Example: values = (-x for x in [2,2,4,4,6])
    • Example: for x in values:
    • Example: print(x) # prints -2 -2 -4 -4 -6 to console/terminal
  • You can also cast a generator comprehension directly to a list.
    • Example: values = (-x for x in [2,2,4,4,6])
    • Example: gen_to_list = list(values)
    • Example: print(gen_to_list) # => [-2, -2, -4, -4, -6]
  • Decorators are a form of syntactic sugar.
  • They make code easier to read while accomplishing clunky syntax.
  • Wrappers are one type of decorator.
  • They’re really useful for adding logging to existing functions without needing to modify them.
    • Example: def log_function(func):
    • Example: def wrapper(*args, **kwargs):
    • Example: print("Entering function", func.__name__)
    • Example: result = func(*args, **kwargs)
    • Example: print("Exiting function", func.__name__)
    • Example: return result
    • Example: return wrapper
    • Example: @log_function # equivalent:
    • Example: def my_function(x,y): # def my_function(x,y):
    • Example: return x+y # return x+y
    • Example: # my_function = log_function(my_function)
  • The decorator @log_function tells us as we begin reading the function definition
  • for my_function that this function will be wrapped with log_function.
  • When function definitions are long, it can be hard to parse the non-decorated
  • assignment at the end of the definition.
    • Example: my_function(2,2) # => "Entering function my_function"
    • Example: # => "4"
    • Example: # => "Exiting function my_function"
  • But there’s a problem.
  • What happens if we try to get some information about my_function?
    • Example: print(my_function.__name__) # => 'wrapper'
    • Example: print(my_function.__code__.co_argcount) # => 0. The argcount is 0 because both arguments in wrapper()'s signature are optional.
  • Because our decorator is equivalent to my_function = log_function(my_function)
  • we’ve replaced information about my_function with information from wrapper
  • Fix this using functools
    • Example: from functools import wraps
    • Example: def log_function(func):
    • Example: @wraps(func) # this ensures docstring, function name, arguments list, etc. are all copied
    • Example: # to the wrapped function - instead of being replaced with wrapper's info
    • Example: def wrapper(*args, **kwargs):
    • Example: print("Entering function", func.__name__)
    • Example: result = func(*args, **kwargs)
    • Example: print("Exiting function", func.__name__)
    • Example: return result
    • Example: return wrapper
    • Example: @log_function
    • Example: def my_function(x,y):
    • Example: return x+y
    • Example: my_function(2,2) # => "Entering function my_function"
    • Example: # => "4"
    • Example: # => "Exiting function my_function"
    • Example: print(my_function.__name__) # => 'my_function'
    • Example: print(my_function.__code__.co_argcount) # => 2
comments powered by Disqus

Related Posts

Introduction to Microservices: the essential guide

Introduction to Microservices: the essential guide

Explore the intricacies of microservices architecture, an innovative approach to designing and deploying applications as a collection of loosely coupled services.

Read More
The 3 Pathways of Modern Application Development on AWS

The 3 Pathways of Modern Application Development on AWS

The 3 Pathways of Modern Application Development on AWS Modern application development is essential for businesses looking to innovate, reduce costs, accelerate time to market, and improve reliability.

Read More
Rest API with Python: FastAPI

Rest API with Python: FastAPI

FastAPI Setup Guide Use the following commands to instal FastAPi on your local environment.

Read More