Let’s see some Python Basics first you can skip it as well.

Type of methods in class

There are three type of methods in class is instance methods(default, first paramerter has to be self and gets passed automatically. It requires object to call these methods, Access class with self.class), class methods (first parameter is cls and class reference gets passed automatically, directly call using classname), static methods (nothing is passed and can be accessed by classname).

Underscore usage.

  self.__xyz = 1 # inside class A
  print A().__xyz # throws error as it is not defined.
  print A()._A__xyz # gives the __xyz value.
  

Variable

xyz ="Something"
xyz = 1  

Everything in Python is object of some class and each variable is just a reference of size 8 byte (can be different in different implementation of Python). But there are some key datatypes defined by Python.

DataTypes

The sizes of each datatype can be different based on different implementation of python.

Number Operations.

Bitwise Operators

Sequence type Operations.

Mutable sequence Operations- List All above are there, here are some more.

Set Operator

Extra immutable operators

Dict operator

Python Module

Module in python are files which can some statements, methods, variable etc. Moduels can import another modules as well. You can reload the module using import importlib; importlib.reload(modulename). Execute Modules - »>python module1.py Access module parameter by, int(sys.argv[1]). Main module should have name \_\_main__.py.

Packages - Packages are folder with __init__.py files, these file can be empty but can also used to set __all__ variable. Use package with dot.

Inheritance.

Private attribute are defined by double underscore and protected are defined by single single underscore. Private can be accesses by mangling the attribute name. Logically anything defined inside functon with self is private. For ex.

  class Person:
  def \_\_init__(self): 
    self.firstname = 'xyz'
    self.\_\_lastname = 'abc'
  ...

  P = Person()
  print(P.__lastname) # will throw, #AttributeError: 'Person' object has no attribute '__lastname'

Python Magic methods.

  def __setattr__(self, name, value):
    self.__dict__[name] = value #right
    self.name = value # wrong, will cause recursion
  class FunctionalList:
    '''A class wrapping a list with some extra functional magic, like head,
    tail, init, last, drop, and take.'''

    def __init__(self, values=None):
        if values is None:
            self.values = []
        else:
            self.values = values

    def __len__(self):
        return len(self.values)

    def __getitem__(self, key):
        # if key is of invalid type or value, the list values will raise the error
        return self.values[key]

    def __setitem__(self, key, value):
        self.values[key] = value

    def __delitem__(self, key):
        del self.values[key]

    def __iter__(self):
        return iter(self.values)

    def __reversed__(self):
        return reversed(self.values)

    def append(self, value):
        self.values.append(value)
    def head(self):
        # get the first element
        return self.values[0]
    def tail(self):
        # get all elements after the first
        return self.values[1:]
    def init(self):
        # get elements up to the last
        return self.values[:-1]
    def last(self):
        # get last element
        return self.values[-1]
    def drop(self, n):
        # get all elements except first n
        return self.values[n:]
    def take(self, n):
        # get first n elements
        return self.values[:n]

Python specials

Sorting classes.

x.sort(key=operator.attrgetter('score'))

Iterator

Taken from stackoverflow, For example

class Counter:
    def __init__(self, low, high):
        self.current = low - 1
        self.high = high

    def __iter__(self):
        return self

    def __next__(self): # Python 2: def next(self)
        self.current += 1
        if self.current < self.high:
            return self.current
        raise StopIteration


for c in Counter(3, 9):
    print(c)

Generator

There is other type of iterator as well, this doesn need a full fledged class.

def counter(low, high):
    current = low
    while current < high:
        yield current
        current += 1

for c in counter(3, 9):
    print(c)

Inheritance.

  class DerivedClassName(BaseClassName1,BaseClassName2..):
    pass

isinstance and issubclass - Tells weather object belong to inhertance hierarchy and a class is subclass of something.

super() - Use this to point to super class.

Exception handling.

We have following keywords, try, except, else, raise,finally.

try:
  print("Hello")
except AppError as error:
  print("Something went wrong",error)
  error_type, error_instance, traceback = sys.exc_info()
else:
  print("Nothing went wrong")
finally:
  print("The 'try except' is finished")
raise ValueError('A very specific bad thing happened.')

Lambda

  x = lambda a, b : a * b
  print(x(5, 6))
  def myfunc(n):
    return lambda a : a * n #returning lambda functions
  mydoubler = myfunc(2)
  print(mydoubler(11))

Global and nonlocal variable

nonlocal points to outer scope variable while global is for outermost which is global.

  x = 0
  def outer():
      x = 1
      def inner():
          nonlocal x # Output 2 if it would have been global x
          x = 2
          print("inner:", x)

      inner()
      print("outer:", x)

  outer()
  print("global:", x)

  # inner: 2
  # outer: 2
  # global: 0

  # output2
  # inner: 2
  # outer: 1
  # global: 2

Compound statements.

  if <expr>:
    <statement(s)>
  elif <expr>:
    <statement(s)>
  else:
    <statement(s)>
  <expr1> if <conditional_expr> else <expr2>
....
  while <expr>:
    <statement(s)>
  else:
    <additional_statement(s)>
....
for x in fruits:
  print(x)
for x in range(2, 30, 3):
  print(x)
....
class controlled_execution:
  def __enter__(self):
      set things up
      return thing
  def __exit__(self, type, value, traceback):
      tear things down

with controlled_execution() as thing:
    some code

with open("x.txt") as f:
    data = f.read()
    do something with data

Plots

Type of plots.

Plot - Plot with lines. matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs) plot([x], y, [fmt], *, data=None, **kwargs) plot([x], y, [fmt], [x2], y2, [fmt2], …, **kwargs)

Subplot - Plot over plot matplotlib.pyplot.subplot(*args, **kwargs) subplot(nrows, ncols, index, **kwargs) subplot(pos, **kwargs) subplot(ax)

Contour Three dimension in 2D with use of color matplotlib.pyplot.contour(*args, data=None, **kwargs)[source] contour([X, Y,] Z, [levels], **kwargs)

Histogram - Used for intervals. matplotlib.pyplot.hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, normed=None, *, data=None, **kwargs)

Bar Chart Same as historgram but is spaced out between bars. matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align=’center’, data=None, **kwargs)

Pie Chart - Something which somes to 1. matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False, *, data=None)

Scatter Plot - Plots points. matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, *, plotnonfinite=False, data=None, **kwargs