Python – Object Oriented Programming – Exceptions

Integration with Python

Operator overloading : comparison

Object equality

 

Variables are references

  • Due to the fact how the objects and variables representing them are stored
    • printing the value of the (customer) object –> prints the memory allocation chunk
    • the value = reference to the memory chunk ))> so when comparing we are comparing the memory chunks

Custom comparison

  • here numpy arrays –> Python considers them equal (as other Python objects like DataFrames
  • How to enforce -> special method __eq__() 

Overloading __eq__()

  • __eq__() is called when 2 objects of a class are compared using ==
  • accepts 2 args, self and other – object to compare
  • returns a Boolean

 

Comparison of objects

  • here the __eq__ method is called and the comparison returns ‘True’ in the 1st case, False in the second case

Other comparisons

Operator Method
== __eq__()
!= __ne__()
>= __ge__()
<= __le__()
> __gt__()
< __lt__()
  • __hash__() to use objects as dictionary keys and in sets

Exercises

 

 

Operator overloading : string representation

Printing an object

  • There are 2 classes that can be a representation
    • __str__() 
      • print(obj), str(obj)
      • informal, for end user
      • string representation
      • print(np.array([1,2,3])) –>[1 2 3]
    • __repr__()
      • repr(obj), printing in console
      • formal, for developer
      • reprocducible representation
      • fallback for print() when __str__() is not available
      • repr(np.array([1,2,3])) –> np.array([1,2,3])

 

Implementation: str

  • the triple ” –> indication for multiline print
  • {} to fill in the values

 

Implementation: repr

  • surround the string arguments with quotation marks in the __repr__() output

String formatting review

Exercise

 

 

Exceptions

Exception handling

    • a = 1 –> a / 0 ==> ZeroDivisionError
    • a = 1 –> a + “Hi” ==> TypeError
    • a = [1,2,3] –> a[5] ==> IndexError
    • a = 1 –> a + b ==> NameError
  • Prevent the program from terminating when a exception is raised
  • Use the try – except – finally :

 

Raising exceptions

Exceptions are classes

Custom exceptions

  • Inherits from Exception or one of its subclasses
  • Usually an empty class

  • the exception interrupted the constructor –> object not created

Catching custom exceptions

Excercises

It’s better to list the except blocks in the increasing order of specificity, i.e. children before parents, otherwise the child exception will be called in the parent except block.