python_cheat_sheet2

Python cheat sheet - iterations

Table of contents

Functions

Specify optional parameters in the end. Specify the default values for optional parameters with = value notation

def func_name(arg1, arg2=None):
    operations
    return value
In [1]:
def func_add_numbers(num1, num2=10):
    return (num1 + num2)
In [2]:
func_add_numbers(2)
Out[2]:
12
In [3]:
func_add_numbers(2,34)
Out[3]:
36
In [4]:
func_add_numbers()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-0d259ef4c90e> in <module>()
----> 1 func_add_numbers()

TypeError: func_add_numbers() missing 1 required positional argument: 'num1'

Classes

Everything is an object in Python including native types. You define class names with camel casing. You define the constructor with special name __init__(). The fields (private) are denoted with _variable_name specification and properties are decorated with @property decorator.

Fields and properties are accessed within the class using self.name notation. This helps differentiate a class field / property from a local variable or method argument of the same name.

A simple class

class MyClass:
    _local_variables = "value"

    def __init__(self, args):  #constructor
        statements
        self._local_variables = args   # assign values to fields

    def func_1(self, args):
        statements

You use this method by instantiating an object.

obj1 = myClass(args_defined_in_constructor)
In [6]:
# Define a class to hold a satellite or aerial imagery file. Its properties give information
# such as location of the ground, area, dimensions, spatial and spectral resolution etc.

class ImageryObject:
    _default_gsd = 5.0
    
    def __init__(self, file_path):
        self._file_path = file_path
        self._gps_location = (3,4)
        
    @property
    def bands(self):
        #count number of bands
        count = 3
        return count
    
    @property
    def gsd(self):
        # logic to calculate the ground sample distance
        gsd = 10.0
        return gsd
    
    @property
    def address(self):
        # logic to reverse geocode the self._gps_location to get address
        # reverse geocode self._gps_location
        address = "123 XYZ Street"
        return address
    
    #class methods
    def display(self):
        #logic to display picture
        print("image is displayed")
    
    def shuffle_bands(self):
        #logic to shift RGB combination
        print("shifting pands")
        self.display()
In [7]:
# class instantiation
img1 = ImageryObject("user\img\file.img") #pass value to constructor
In [8]:
img1.address
Out[8]:
'123 XYZ Street'
In [9]:
img1._default_gsd
Out[9]:
5.0
In [10]:
img1._gps_location
Out[10]:
(3, 4)
In [11]:
img1.shuffle_bands()
shifting pands
image is displayed
In [12]:
# Get help on any object. Only public methods, properties are displayed.
# fields are private, properties are public. Class variables beginning with _ are private fields.
help(img1)
Help on ImageryObject in module __main__ object:

class ImageryObject(builtins.object)
 |  Methods defined here:
 |  
 |  __init__(self, file_path)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  display(self)
 |      #class methods
 |  
 |  shuffle_bands(self)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  address
 |  
 |  bands
 |  
 |  gsd

Exception handling

Exceptions are classes. You can define your own by inheriting from Exception class.

try:
    statements

except Exception_type1 as e1:
    handling statements

except Exception_type2 as e2:
    specific handling statements

except Exception as generic_ex:
    generic handling statements

else:
    some more statements

finally:
    default statements which will always be executed
In [13]:
try:
    img2 = ImageryObject("user\img\file2.img")
    img2.display()
except:
    print("something bad happened")
image is displayed
In [14]:
try:
    img2 = ImageryObject("user\img\file2.img")
    img2.display()
except:
    print("something bad happened")
else:
    print("else block")
finally:
    print("finally block")
image is displayed
else block
finally block
In [15]:
try:
    img2 = ImageryObject()
    img2.display()
except:
    print("something bad happened")
else:
    print("else block")
finally:
    print("finally block")
something bad happened
finally block
In [21]:
try:
    img2 = ImageryObject()
    img2.display()

except Exception as ex:
    print("something bad happened")
    print("exactly what whent bad? : " + str(ex))
something bad happened
exactly what whent bad? : __init__() missing 1 required positional argument: 'file_path'
In [22]:
try:
    img2 = ImageryObject('path')
    img2.dddisplay()

except TypeError as terr:
    print("looks like you forgot a parameter")
except Exception as ex:
    print("nope, it went worng here: " + str(ex))
nope, it went worng here: 'ImageryObject' object has no attribute 'dddisplay'
In [ ]: