In [1]:
Agenda = '''
1. Object Oriented Programming
2. class
3. object
4. method with self
5. constructor __init__
6. object variable
7. class variable 
8. object variable vs class variable
9. inheritance
10. Polymorphism : overriding 
11. user of super
12. Application Developement using Object Oriented Programming
13. Module
14. User Define 
15. Built in Modules : os, sys, pickle, json
16. File Handling 
17. Car Application Assignment 
18. Group Discussion and Summary
'''

Class in Python

Class is a template or blueprint, which encapsulate data and method together. 
In [8]:
class TargetRetail:  # TargetRetail is class with camel case
    '''Retail Class for Target Stores'''
    

Object in Python

Object is an instance of class. 
In [7]:
TR1 = TargetRetail()

# TR1 is an object of class TargetRetail

print(TR1)
print(TR1.__doc__)
<__main__.TargetRetail object at 0x1116f4490>
Retail Class for Target Stores
In [5]:
help(TR1)
Help on TargetRetail in module __main__ object:

class TargetRetail(builtins.object)
 |  Retail Class for Target Stores
 |  
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

Function vs Method in class

In [9]:
class TargetRetail:  # TargetRetail is class with camel case
    '''Retail Class for Target Stores'''
    
    def info():
        '''TargetRetail Store Information'''
        print("TargetRetail Store Information")
        
    
    
TR1 = TargetRetail()

# TR1 is an object of class TargetRetail

TR1.info()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-c2378dc02a04> in <module>
     12 # TR1 is an object of class TargetRetail
     13 
---> 14 TR1.info()

TypeError: info() takes 0 positional arguments but 1 was given

Method

Method is binded with class using self.
self is first parameter  or argument to all methods. 
self is reference to instance of class. It's not keyword.
In [10]:
class TargetRetail:  # TargetRetail is class with camel case
    '''Retail Class for Target Stores'''
    
    def info(self):
        '''TargetRetail Store Information'''
        print("TargetRetail Store Information")
        
# self is reference to instance of class. It's not keyword.
    
TR1 = TargetRetail()

# TR1 is an object of class TargetRetail

TR1.info()
TargetRetail Store Information

Local Variable vs Object Variable

We define object variable using self inside all methods.
Object Variable accessible to all objects.
Object Variable can be shared with other methods inside class.
After inheritance they are accessible to other classes too. 

Local variables are not accessible to object.
In [13]:
class TargetRetail:  # TargetRetail is class with camel case
    '''Retail Class for Target Stores'''
    
    def info(self, city, state ):
        '''TargetRetail Store Information'''
        
        print("TargetRetail Store Information")
        print("TargetRetail City is ",city)
        print("TargetRetail State is %s "%state)
        
        # city and state are local variable

        
TR1 = TargetRetail()

# TR1 is an object of class TargetRetail

TR1.info('Bangalore','Karanataka')
print(TR1.city)
TargetRetail Store Information
TargetRetail City is  Bangalore
TargetRetail State is Karanataka 
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-d4a69780390e> in <module>
     17 
     18 TR1.info('Bangalore','Karanataka')
---> 19 print(TR1.city)

AttributeError: 'TargetRetail' object has no attribute 'city'

Object Variable

Object variable is accessible to object only and not to class.
In [14]:
class TargetRetail:  # TargetRetail is class with camel case
    '''Retail Class for Target Stores'''
    
    def info(self, city, state ):
        '''TargetRetail Store Information'''
        
        self.city = city  # object variable
        self.state = state
        print("TargetRetail Store Information")
        print("TargetRetail City is ",city)
        print("TargetRetail State is %s "%state)
        
        # city and state are local variable

        
TR1 = TargetRetail()

# TR1 is an object of class TargetRetail

TR1.info('Bangalore','Karanataka')
print(TR1.city, TR1.state)
TargetRetail Store Information
TargetRetail City is  Bangalore
TargetRetail State is Karanataka 
Bangalore Karanataka

Constructor Method

Class has default construtor __init__ (double underscore ).
__init__ is built in method of class.
It allows to instialise class. 
Means it allows to pass arguments to class. 
Whenever you create new object, constructor method get called automatically.
In [22]:
class TargetRetail:  # TargetRetail is class with camel case
    '''Retail Class for Target Stores'''
    
    def __init__(self, rname, country):
        '''Initialise TargetRetails class with argument'''
        self.rname = rname  # object variable
        self.country = country
    
    def info(self, city, state ):
        '''TargetRetail Store Information'''
        
        self.city = city  # object variable
        self.state = state
        
        print("\n TargetRetail Store name is %s and \
country is %s "%(self.rname, self.country))
              
        print("\nTargetRetail City is ",city)
        print("\nTargetRetail State is %s "%state)
        
        # city and state are local variable

        
TR1 = TargetRetail('TargetRetail','India')
TR2 = TargetRetail('TargetRetail','USA')

# TR1 is an object of class TargetRetail

TR1.info('Bangalore','Karanataka')
              
TR2.info('Chicago','NewYork')
 TargetRetail Store name is TargetRetail and country is India 

TargetRetail City is  Bangalore

TargetRetail State is Karanataka 

 TargetRetail Store name is TargetRetail and country is USA 

TargetRetail City is  Chicago

TargetRetail State is NewYork 

Class Variable / Attribute

It is accessible to all class method.
Class variable is accessible to class as well as object.
Class variable should be written inside class.
Class variable is like static variable in java / cpp.
In [28]:
%%writefile targetmod.py

class TargetRetail:  # TargetRetail is class with camel case
    '''Retail Class for Target Stores'''
    
    storeid = 100   # Class varible 
    
    def __init__(self, rname, country):
        '''Initialise TargetRetails class with argument'''
        TargetRetail.storeid += 1
        self.rname = rname  # object variable
        self.country = country
        print("Retail Store id is TR00%d "%self.storeid)
    
    def info(self, city, state ):
        '''TargetRetail Store Information'''
        
        self.city = city  # object variable
        self.state = state
        
        print("\n TargetRetail Store name is %s and \
country is %s "%(self.rname, self.country))
              
        print("\nTargetRetail City is ",city)
        print("\nTargetRetail State is %s "%state)
        # city and state are local variable

        
if __name__ == '__main__':
    
    TR1 = TargetRetail('TargetRetail','India')
    TR1.info('Bangalore','Karanataka')
    TR2 = TargetRetail('TargetRetail','USA')
    TR2.info('Chicago','NewYork')
Overwriting targetmod.py
In [29]:
run targetmod.py
Retail Store id is TR00101 

 TargetRetail Store name is TargetRetail and country is India 

TargetRetail City is  Bangalore

TargetRetail State is Karanataka 
Retail Store id is TR00102 

 TargetRetail Store name is TargetRetail and country is USA 

TargetRetail City is  Chicago

TargetRetail State is NewYork 
In [31]:
import targetmod

dir(targetmod)
Out[31]:
['TR1',
 'TR2',
 'TargetRetail',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__']
In [32]:
help(targetmod)
Help on module targetmod:

NAME
    targetmod

CLASSES
    builtins.object
        TargetRetail
    
    class TargetRetail(builtins.object)
     |  TargetRetail(rname, country)
     |  
     |  Retail Class for Target Stores
     |  
     |  Methods defined here:
     |  
     |  __init__(self, rname, country)
     |      Initialise TargetRetails class with argument
     |  
     |  info(self, city, state)
     |      TargetRetail Store Information
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  storeid = 102

DATA
    TR1 = <targetmod.TargetRetail object>
    TR2 = <targetmod.TargetRetail object>

FILE
    /Users/surendra/targetmod.py


In [33]:
help(targetmod.TargetRetail)
Help on class TargetRetail in module targetmod:

class TargetRetail(builtins.object)
 |  TargetRetail(rname, country)
 |  
 |  Retail Class for Target Stores
 |  
 |  Methods defined here:
 |  
 |  __init__(self, rname, country)
 |      Initialise TargetRetails class with argument
 |  
 |  info(self, city, state)
 |      TargetRetail Store Information
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  storeid = 102

In [34]:
cd __pycache__/
/Users/surendra/__pycache__
In [35]:
ls targe*
targetmod.cpython-37.pyc
In [36]:
cd ..
/Users/surendra
In [37]:
from targetmod import TargetRetail


TR3 = TargetRetail('TargetRetail','UK')
TR3.info('London','UK')

TR4 = TargetRetail('TargetRetail','USA')
TR4.info('Chicago','NewYork')
Retail Store id is TR00103 

 TargetRetail Store name is TargetRetail and country is UK 

TargetRetail City is  London

TargetRetail State is UK 
Retail Store id is TR00104 

 TargetRetail Store name is TargetRetail and country is USA 

TargetRetail City is  Chicago

TargetRetail State is NewYork 
In [38]:
import targetmod as tr  # Alias to targetmod

TR3 = tr.TargetRetail('TargetRetail','UK')
TR3.info('London','UK')

TR4 = tr.TargetRetail('TargetRetail','USA')
TR4.info('Chicago','NewYork')
Retail Store id is TR00105 

 TargetRetail Store name is TargetRetail and country is UK 

TargetRetail City is  London

TargetRetail State is UK 
Retail Store id is TR00106 

 TargetRetail Store name is TargetRetail and country is USA 

TargetRetail City is  Chicago

TargetRetail State is NewYork 
In [39]:
from targetmod import *


TR3 = TargetRetail('TargetRetail','UK')
TR3.info('London','UK')

TR4 = TargetRetail('TargetRetail','USA')
TR4.info('Chicago','NewYork')
Retail Store id is TR00107 

 TargetRetail Store name is TargetRetail and country is UK 

TargetRetail City is  London

TargetRetail State is UK 
Retail Store id is TR00108 

 TargetRetail Store name is TargetRetail and country is USA 

TargetRetail City is  Chicago

TargetRetail State is NewYork 

Inheritance

It allows you to access the properties of parent / super / base class in a child / subclass / derived class.
Reusability of class, data and methods.
In [42]:
from targetmod import TargetRetail

class Customer(TargetRetail):
    '''Customer class is inherited class ( child class)'''
    
    def cinfo(self, cname, cloc):
        '''Customer Information'''
        self.cname = cname
        self.cloc = cloc
        print("\nCustomer name is %s and location is %s"%(cname,cloc))
    

CR1 = Customer('TargetRetail','UK')
CR1.info('London','UK')
CR1.cinfo('Surendra','Pune')

CR2 = Customer('TargetRetail','USA')
CR2.info('Chicago','NewYork')
CR2.cinfo('Satish','Chicago')
Retail Store id is TR00113 

 TargetRetail Store name is TargetRetail and country is UK 

TargetRetail City is  London

TargetRetail State is UK 

Customer name is Surendra and location is Pune
Retail Store id is TR00114 

 TargetRetail Store name is TargetRetail and country is USA 

TargetRetail City is  Chicago

TargetRetail State is NewYork 

Customer name is Satish and location is Chicago

Polymorphism :

Overriding : It overrides parent class method by 
child class method. 

child class method name and parent class method name is same.
In [43]:
from targetmod import TargetRetail

class Customer(TargetRetail):
    '''Customer class is inherited class ( child class)'''
    
    def info(self, cname, cloc):
        '''Customer Information'''
        self.cname = cname
        self.cloc = cloc
        print("\nCustomer name is %s and location is %s"%(cname,cloc))
    

CR1 = Customer('TargetRetail','UK')
#CR1.info('London','UK')
CR1.info('Surendra','Pune')

CR2 = Customer('TargetRetail','USA')
#CR2.info('Chicago','NewYork')
CR2.info('Satish','Chicago')
Retail Store id is TR00115 

Customer name is Surendra and location is Pune
Retail Store id is TR00116 

Customer name is Satish and location is Chicago

super method

To access super class method in child class.
In [47]:
from targetmod import TargetRetail

class Customer(TargetRetail):
    '''Customer class is inherited class ( child class)'''
    
    def info(self, city, state, cname, cloc):
        '''Customer Information'''
        TargetRetail.info(self,city,state)
        self.cname = cname
        self.cloc = cloc
        print("\nCustomer name is %s and location is %s"%(cname,cloc))
    

CR1 = Customer('TargetRetail','UK')
CR1.info('London','UK','Surendra','Pune')

CR2 = Customer('TargetRetail','USA')
CR2.info('Chicago','NewYork','Satish','Chicago')
Retail Store id is TR00120 

 TargetRetail Store name is TargetRetail and country is UK 

TargetRetail City is  London

TargetRetail State is UK 

Customer name is Surendra and location is Pune
Retail Store id is TR00121 

 TargetRetail Store name is TargetRetail and country is USA 

TargetRetail City is  Chicago

TargetRetail State is NewYork 

Customer name is Satish and location is Chicago
In [53]:
from targetmod import TargetRetail

class Customer(TargetRetail):
    '''Customer class is inherited class ( child class)'''
    
    def info(self, city, state, cname, cloc):
        '''Customer Information'''
        #super(Customer, self).info(city,state)
        super().info(city,state)
        self.cname = cname
        self.cloc = cloc
        print("\nCustomer name is %s and location is %s"%(cname,cloc))
    

CR1 = Customer('TargetRetail','UK')
CR1.info('London','UK','Surendra','Pune')

CR2 = Customer('TargetRetail','USA')
CR2.info('Chicago','NewYork','Satish','Chicago')
Retail Store id is TR00130 

 TargetRetail Store name is TargetRetail and country is UK 

TargetRetail City is  London

TargetRetail State is UK 

Customer name is Surendra and location is Pune
Retail Store id is TR00131 

 TargetRetail Store name is TargetRetail and country is USA 

TargetRetail City is  Chicago

TargetRetail State is NewYork 

Customer name is Satish and location is Chicago
In [55]:
from targetmod import TargetRetail

class Employee(TargetRetail):
    '''Employee class is inherited class ( child class)'''
    
    def info(self, city, state, ename, cloc):
        '''Employee Information'''
        #super(Employee, self).info(city,state)
        super().info(city,state)
        self.ename = ename
        self.cloc = cloc
        print("\nEmployee name is %s and location is %s"%(ename,cloc))
    

E1 = Employee('TargetRetail','UK')
E1.info('London','UK','Surendra','Pune')

E2 = Employee('TargetRetail','USA')
E2.info('Chicago','NewYork','Satish','Chicago')
Retail Store id is TR00134 

 TargetRetail Store name is TargetRetail and country is UK 

TargetRetail City is  London

TargetRetail State is UK 

Employee name is Surendra and location is Pune
Retail Store id is TR00135 

 TargetRetail Store name is TargetRetail and country is USA 

TargetRetail City is  Chicago

TargetRetail State is NewYork 

Employee name is Satish and location is Chicago

Built in Modules

In [57]:
import os

#dir(os)
In [58]:
os.getcwd()
Out[58]:
'/Users/surendra'
In [59]:
os.mkdir('targetnew')
In [60]:
cd targetnew/
/Users/surendra/targetnew
In [61]:
cd ..
/Users/surendra
In [62]:
os.system('ls -l')
Out[62]:
0
In [65]:
os.rmdir('targetnew')
In [66]:
os.chdir('..')
In [67]:
pwd
Out[67]:
'/Users'
In [68]:
os.chdir('Surendra')
In [69]:
pwd
Out[69]:
'/Users/surendra'

sys module

In [70]:
import sys

sys.platform
Out[70]:
'darwin'
In [71]:
sys.version
Out[71]:
'3.7.6 (default, Jan  8 2020, 13:42:34) \n[Clang 4.0.1 (tags/RELEASE_401/final)]'
In [72]:
sys.version_info
Out[72]:
sys.version_info(major=3, minor=7, micro=6, releaselevel='final', serial=0)
In [73]:
sys.path
Out[73]:
['/Users/surendra',
 '/Users/surendra/anaconda3/lib/python37.zip',
 '/Users/surendra/anaconda3/lib/python3.7',
 '/Users/surendra/anaconda3/lib/python3.7/lib-dynload',
 '',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/aeosa',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/Django-2.1.3-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/PyHamcrest-1.9.0-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/Quandl-3.4.5-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/inflection-0.3.1-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/jenkinsapi-0.3.8-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/Pattern-3.6-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/CherryPy-18.1.1-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/python_docx-0.8.10-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/pdfminer.six-20181108-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/feedparser-5.2.1-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/ChatterBot-1.0.5-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/PyYAML-5.1.1-py3.7-macosx-10.7-x86_64.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/Pint-0.9-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/chatterbot_corpus-1.2.0-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/scapy-git_archive.deva86419391-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/flake8-3.7.8-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/entrypoints-0.3-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/IPython/extensions',
 '/Users/surendra/.ipython']
In [74]:
sys.path.append('/Users/surendra/Target/')
In [75]:
sys.path
Out[75]:
['/Users/surendra',
 '/Users/surendra/anaconda3/lib/python37.zip',
 '/Users/surendra/anaconda3/lib/python3.7',
 '/Users/surendra/anaconda3/lib/python3.7/lib-dynload',
 '',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/aeosa',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/Django-2.1.3-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/PyHamcrest-1.9.0-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/Quandl-3.4.5-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/inflection-0.3.1-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/jenkinsapi-0.3.8-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/Pattern-3.6-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/CherryPy-18.1.1-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/python_docx-0.8.10-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/pdfminer.six-20181108-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/feedparser-5.2.1-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/ChatterBot-1.0.5-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/PyYAML-5.1.1-py3.7-macosx-10.7-x86_64.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/Pint-0.9-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/chatterbot_corpus-1.2.0-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/scapy-git_archive.deva86419391-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/flake8-3.7.8-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/entrypoints-0.3-py3.7.egg',
 '/Users/surendra/anaconda3/lib/python3.7/site-packages/IPython/extensions',
 '/Users/surendra/.ipython',
 '/Users/surendra/Target/']
In [76]:
help(sys)
Help on built-in module sys:

NAME
    sys

MODULE REFERENCE
    https://docs.python.org/3.7/library/sys
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.
    
    Dynamic objects:
    
    argv -- command line arguments; argv[0] is the script pathname if known
    path -- module search path; path[0] is the script directory, else ''
    modules -- dictionary of loaded modules
    
    displayhook -- called to show results in an interactive session
    excepthook -- called to handle any uncaught exception other than SystemExit
      To customize printing in an interactive session or to install a custom
      top-level exception handler, assign other functions to replace these.
    
    stdin -- standard input file object; used by input()
    stdout -- standard output file object; used by print()
    stderr -- standard error object; used for error messages
      By assigning other file objects (or objects that behave like files)
      to these, it is possible to redirect all of the interpreter's I/O.
    
    last_type -- type of last uncaught exception
    last_value -- value of last uncaught exception
    last_traceback -- traceback of last uncaught exception
      These three are only available in an interactive session after a
      traceback has been printed.
    
    Static objects:
    
    builtin_module_names -- tuple of module names built into this interpreter
    copyright -- copyright notice pertaining to this interpreter
    exec_prefix -- prefix used to find the machine-specific Python library
    executable -- absolute path of the executable binary of the Python interpreter
    float_info -- a named tuple with information about the float implementation.
    float_repr_style -- string indicating the style of repr() output for floats
    hash_info -- a named tuple with information about the hash algorithm.
    hexversion -- version information encoded as a single integer
    implementation -- Python implementation information.
    int_info -- a named tuple with information about the int implementation.
    maxsize -- the largest supported length of containers.
    maxunicode -- the value of the largest Unicode code point
    platform -- platform identifier
    prefix -- prefix used to find the Python library
    thread_info -- a named tuple with information about the thread implementation.
    version -- the version of this interpreter as a string
    version_info -- version information as a named tuple
    __stdin__ -- the original stdin; don't touch!
    __stdout__ -- the original stdout; don't touch!
    __stderr__ -- the original stderr; don't touch!
    __displayhook__ -- the original displayhook; don't touch!
    __excepthook__ -- the original excepthook; don't touch!
    
    Functions:
    
    displayhook() -- print an object to the screen, and save it in builtins._
    excepthook() -- print an exception and its traceback to sys.stderr
    exc_info() -- return thread-safe information about the current exception
    exit() -- exit the interpreter by raising SystemExit
    getdlopenflags() -- returns flags to be used for dlopen() calls
    getprofile() -- get the global profiling function
    getrefcount() -- return the reference count for an object (plus one :-)
    getrecursionlimit() -- return the max recursion depth for the interpreter
    getsizeof() -- return the size of an object in bytes
    gettrace() -- get the global debug tracing function
    setcheckinterval() -- control how often the interpreter checks for events
    setdlopenflags() -- set the flags to be used for dlopen() calls
    setprofile() -- set the global profiling function
    setrecursionlimit() -- set the max recursion depth for the interpreter
    settrace() -- set the global debug tracing function

FUNCTIONS
    __breakpointhook__ = breakpointhook(...)
        breakpointhook(*args, **kws)
        
        This hook function is called by built-in breakpoint().
    
    __displayhook__ = displayhook(...)
        displayhook(object) -> None
        
        Print an object to sys.stdout and also save it in builtins._
    
    __excepthook__ = excepthook(...)
        excepthook(exctype, value, traceback) -> None
        
        Handle an exception by displaying it with a traceback on sys.stderr.
    
    breakpointhook(...)
        breakpointhook(*args, **kws)
        
        This hook function is called by built-in breakpoint().
    
    call_tracing(...)
        call_tracing(func, args) -> object
        
        Call func(*args), while tracing is enabled.  The tracing state is
        saved, and restored afterwards.  This is intended to be called from
        a debugger from a checkpoint, to recursively debug some other code.
    
    callstats(...)
        callstats() -> tuple of integers
        
        Return a tuple of function call statistics, if CALL_PROFILE was defined
        when Python was built.  Otherwise, return None.
        
        When enabled, this function returns detailed, implementation-specific
        details about the number of function calls executed. The return value is
        a 11-tuple where the entries in the tuple are counts of:
        0. all function calls
        1. calls to PyFunction_Type objects
        2. PyFunction calls that do not create an argument tuple
        3. PyFunction calls that do not create an argument tuple
           and bypass PyEval_EvalCodeEx()
        4. PyMethod calls
        5. PyMethod calls on bound methods
        6. PyType calls
        7. PyCFunction calls
        8. generator calls
        9. All other calls
        10. Number of stack pops performed by call_function()
    
    exc_info(...)
        exc_info() -> (type, value, traceback)
        
        Return information about the most recent exception caught by an except
        clause in the current stack frame or in an older stack frame.
    
    exit(...)
        exit([status])
        
        Exit the interpreter by raising SystemExit(status).
        If the status is omitted or None, it defaults to zero (i.e., success).
        If the status is an integer, it will be used as the system exit status.
        If it is another kind of object, it will be printed and the system
        exit status will be one (i.e., failure).
    
    get_asyncgen_hooks(...)
        get_asyncgen_hooks()
        
        Return a namedtuple of installed asynchronous generators hooks (firstiter, finalizer).
    
    get_coroutine_origin_tracking_depth()
        Check status of origin tracking for coroutine objects in this thread.
    
    get_coroutine_wrapper(...)
        get_coroutine_wrapper()
        
        Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper.
    
    getallocatedblocks(...)
        getallocatedblocks() -> integer
        
        Return the number of memory blocks currently allocated, regardless of their
        size.
    
    getcheckinterval(...)
        getcheckinterval() -> current check interval; see setcheckinterval().
    
    getdefaultencoding(...)
        getdefaultencoding() -> string
        
        Return the current default string encoding used by the Unicode 
        implementation.
    
    getdlopenflags(...)
        getdlopenflags() -> int
        
        Return the current value of the flags that are used for dlopen calls.
        The flag constants are defined in the os module.
    
    getfilesystemencodeerrors(...)
        getfilesystemencodeerrors() -> string
        
        Return the error mode used to convert Unicode filenames in
        operating system filenames.
    
    getfilesystemencoding(...)
        getfilesystemencoding() -> string
        
        Return the encoding used to convert Unicode filenames in
        operating system filenames.
    
    getprofile(...)
        getprofile()
        
        Return the profiling function set with sys.setprofile.
        See the profiler chapter in the library manual.
    
    getrecursionlimit(...)
        getrecursionlimit()
        
        Return the current value of the recursion limit, the maximum depth
        of the Python interpreter stack.  This limit prevents infinite
        recursion from causing an overflow of the C stack and crashing Python.
    
    getrefcount(...)
        getrefcount(object) -> integer
        
        Return the reference count of object.  The count returned is generally
        one higher than you might expect, because it includes the (temporary)
        reference as an argument to getrefcount().
    
    getsizeof(...)
        getsizeof(object, default) -> int
        
        Return the size of object in bytes.
    
    getswitchinterval(...)
        getswitchinterval() -> current thread switch interval; see setswitchinterval().
    
    gettrace(...)
        gettrace()
        
        Return the global debug tracing function set with sys.settrace.
        See the debugger chapter in the library manual.
    
    intern(...)
        intern(string) -> string
        
        ``Intern'' the given string.  This enters the string in the (global)
        table of interned strings whose purpose is to speed up dictionary lookups.
        Return the string itself or the previously interned string object with the
        same value.
    
    is_finalizing(...)
        is_finalizing()
        Return True if Python is exiting.
    
    set_asyncgen_hooks(...)
        set_asyncgen_hooks(*, firstiter=None, finalizer=None)
        
        Set a finalizer for async generators objects.
    
    set_coroutine_origin_tracking_depth(depth)
        Enable or disable origin tracking for coroutine objects in this thread.
        
        Coroutine objects will track 'depth' frames of traceback information about
        where they came from, available in their cr_origin attribute. Set depth of 0
        to disable.
    
    set_coroutine_wrapper(...)
        set_coroutine_wrapper(wrapper)
        
        Set a wrapper for coroutine objects.
    
    setcheckinterval(...)
        setcheckinterval(n)
        
        Tell the Python interpreter to check for asynchronous events every
        n instructions.  This also affects how often thread switches occur.
    
    setdlopenflags(...)
        setdlopenflags(n) -> None
        
        Set the flags used by the interpreter for dlopen calls, such as when the
        interpreter loads extension modules.  Among other things, this will enable
        a lazy resolving of symbols when importing a module, if called as
        sys.setdlopenflags(0).  To share symbols across extension modules, call as
        sys.setdlopenflags(os.RTLD_GLOBAL).  Symbolic names for the flag modules
        can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).
    
    setprofile(...)
        setprofile(function)
        
        Set the profiling function.  It will be called on each function call
        and return.  See the profiler chapter in the library manual.
    
    setrecursionlimit(...)
        setrecursionlimit(n)
        
        Set the maximum depth of the Python interpreter stack to n.  This
        limit prevents infinite recursion from causing an overflow of the C
        stack and crashing Python.  The highest possible limit is platform-
        dependent.
    
    setswitchinterval(...)
        setswitchinterval(n)
        
        Set the ideal thread switching delay inside the Python interpreter
        The actual frequency of switching threads can be lower if the
        interpreter executes long sequences of uninterruptible code
        (this is implementation-specific and workload-dependent).
        
        The parameter must represent the desired switching delay in seconds
        A typical value is 0.005 (5 milliseconds).
    
    settrace(...)
        settrace(function)
        
        Set the global debug tracing function.  It will be called on each
        function call.  See the debugger chapter in the library manual.

DATA
    __stderr__ = <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF...
    __stdin__ = <_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8...
    __stdout__ = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF...
    abiflags = 'm'
    api_version = 1013
    argv = ['/Users/surendra/anaconda3/lib/python3.7/site-packages/ipykern...
    base_exec_prefix = '/Users/surendra/anaconda3'
    base_prefix = '/Users/surendra/anaconda3'
    builtin_module_names = ('_abc', '_ast', '_codecs', '_collections', '_f...
    byteorder = 'little'
    copyright = 'Copyright (c) 2001-2019 Python Software Foundati...ematis...
    displayhook = <ipykernel.displayhook.ZMQShellDisplayHook object>
    dont_write_bytecode = False
    exec_prefix = '/Users/surendra/anaconda3'
    executable = '/Users/surendra/anaconda3/bin/python'
    flags = sys.flags(debug=0, inspect=0, interactive=0, opt...ation=1, is...
    float_info = sys.float_info(max=1.7976931348623157e+308, max_...epsilo...
    float_repr_style = 'short'
    hash_info = sys.hash_info(width=64, modulus=2305843009213693...iphash2...
    hexversion = 50792176
    implementation = namespace(_multiarch='darwin', cache_tag='cpytho...in...
    int_info = sys.int_info(bits_per_digit=30, sizeof_digit=4)
    last_value = NameError("name 'Cusomer' is not defined")
    maxsize = 9223372036854775807
    maxunicode = 1114111
    meta_path = [<class '_frozen_importlib.BuiltinImporter'>, <class '_fro...
    modules = {'IPython': <module 'IPython' from '/Users/surendra/anaconda...
    path = ['/Users/surendra', '/Users/surendra/anaconda3/lib/python37.zip...
    path_hooks = [<class 'zipimport.zipimporter'>, <function FileFinder.pa...
    path_importer_cache = {'/Users/surendra': FileFinder('/Users/surendra'...
    platform = 'darwin'
    prefix = '/Users/surendra/anaconda3'
    ps1 = 'In : '
    ps2 = '...: '
    ps3 = 'Out: '
    stderr = <ipykernel.iostream.OutStream object>
    stdin = <_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>
    stdout = <ipykernel.iostream.OutStream object>
    thread_info = sys.thread_info(name='pthread', lock='mutex+cond', versi...
    version = '3.7.6 (default, Jan  8 2020, 13:42:34) \n[Clang 4.0.1 (tags...
    version_info = sys.version_info(major=3, minor=7, micro=6, releaseleve...
    warnoptions = []

FILE
    (built-in)


pickle module

It help to serialise python object into series of bytes and 
series of bytes into python object without much modification. 
In [78]:
import pickle

#help(pickle)
In [85]:
import pickle
import pprint  # pretty print format for object

data = { 'name' : 'surendra', 'loc' : ['pune','maharashtra'],
       'ages' : (42, 23) }

pprint.pprint(data)

pickle_data = pickle.dumps(data)

print('pickle data:', pickle_data)

print(type(pickle_data))

unpickle_data = pickle.loads(pickle_data)

print("Unpickel data is ", unpickle_data)

print("is data got modified ? ", data == unpickle_data)

print("is it same? ", data is unpickle_data)
{'ages': (42, 23), 'loc': ['pune', 'maharashtra'], 'name': 'surendra'}
pickle data: b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x08\x00\x00\x00surendraq\x02X\x03\x00\x00\x00locq\x03]q\x04(X\x04\x00\x00\x00puneq\x05X\x0b\x00\x00\x00maharashtraq\x06eX\x04\x00\x00\x00agesq\x07K*K\x17\x86q\x08u.'
<class 'bytes'>
Unpickel data is  {'name': 'surendra', 'loc': ['pune', 'maharashtra'], 'ages': (42, 23)}
is data got modified ?  True
is it same?  False

json module

Java Script Object Serialisation 
In [86]:
import json

import pprint  # pretty print format for object

data = { 'name' : 'surendra', 'loc' : ['pune','maharashtra'],
       'ages' : (42, 23) }

pprint.pprint(data)

pickle_data = json.dumps(data)

print('pickle data:', pickle_data)

print(type(pickle_data))

unpickle_data = json.loads(pickle_data)

print("Unpickel data is ", unpickle_data)

print("is data got modified ? ", data == unpickle_data)

print("is it same? ", data is unpickle_data)
{'ages': (42, 23), 'loc': ['pune', 'maharashtra'], 'name': 'surendra'}
pickle data: {"name": "surendra", "loc": ["pune", "maharashtra"], "ages": [42, 23]}
<class 'str'>
Unpickel data is  {'name': 'surendra', 'loc': ['pune', 'maharashtra'], 'ages': [42, 23]}
is data got modified ?  False
is it same?  False

File Handling

In [88]:
Agenda = '''
1. Object Oriented Programming
2. class
3. object
4. method with self
5. constructor __init__
6. object variable
7. class variable 
8. object variable vs class variable
9. inheritance
10. Polymorphism : overriding 
11. user of super
12. Application Developement using Object Oriented Programming
13. Module
14. User Define 
15. Built in Modules : os, sys, pickle, json
16. File Handling 
17. Exception Exception Handling
18. Group Discussion and Summary
'''


# step1 Create and write data into file.

with open("agenda_oops.txt",'w+') as fileobj:
    fileobj.write(Agenda)
    
    
# step2 Read Content of the file 

with open("agenda_oops.txt") as fileobj:
    print(fileobj.read())
    
    
# step3 Append New content into file

with open("agenda_oops.txt",'a+') as fileobj:
    fileobj.write("File Handling is Awsome !!\n")
    
    
# step4 Read Content of the file 

with open("agenda_oops.txt") as fileobj:
    print(fileobj.read())
    
1. Object Oriented Programming
2. class
3. object
4. method with self
5. constructor __init__
6. object variable
7. class variable 
8. object variable vs class variable
9. inheritance
10. Polymorphism : overriding 
11. user of super
12. Application Developement using Object Oriented Programming
13. Module
14. User Define 
15. Built in Modules : os, sys, pickle, json
16. File Handling 
17. Exception Exception Handling
18. Group Discussion and Summary


1. Object Oriented Programming
2. class
3. object
4. method with self
5. constructor __init__
6. object variable
7. class variable 
8. object variable vs class variable
9. inheritance
10. Polymorphism : overriding 
11. user of super
12. Application Developement using Object Oriented Programming
13. Module
14. User Define 
15. Built in Modules : os, sys, pickle, json
16. File Handling 
17. Exception Exception Handling
18. Group Discussion and Summary
File Handling is Awsome !!

In [89]:
pwd
Out[89]:
'/Users/surendra'
In [ ]:
# %load car_design_mod.py

class CarDesign:
    '''This is a CarDesign Class'''
    
    chasis_no = 100

    def __init__(self, name):
        '''Initialising CarDesign Class'''
        self.name = name # Object Variable 
        CarDesign.chasis_no += 1
        print("Car Chasis number",self.chasis_no)
        
    def info(self):
        '''This is an Information function'''
        print("Car Information")
        print("Car Design ",self.name)
        

if __name__ == '__main__':
    Car1 = CarDesign('Honda Car')
    Car1.info()
    Car2 = CarDesign('TATA Car')
    Car2.info()
    Car3 = CarDesign('INNOVA Car')
    Car3.info()
In [ ]:
# %load carapp.py
'''
Car Application with Power Window and Power Break Features.
'''

class Car:
    '''This is a Car class'''
    
    chassis_no = 0  # Class Variable 
    
    def __init__(self, cname, cmodel ):
        '''Initialisation of Car Class'''
        Car.chassis_no += 1  # Increment Chassis number for every object
        self.cname = cname # Object Variable 
        self.cmodel = cmodel 
        print("Chassis Number is : %d"%Car.chassis_no)
        
    def info(self):
        '''Car Information Method'''
        print("Car name is %s"%self.cname)
        print("Car model is %s"%self.cmodel)
        
        
class DeluxCar(Car):
    '''DeluxCar Class with some addvance feature'''
    
    def power_window(self):
        '''Power Window Method'''
        print("Power Window in Car")
        
    def power_break(self):
        '''Power Break Method'''
        print("Power Break in Car")
        
    
def Main():
    Obj1 = DeluxCar('Honda','Mobilio')
    Obj1.info()
    Obj1.power_window()
    Obj1.power_break()
    Obj2 = DeluxCar('Honda','Jaz')
    Obj2.info()
    Obj2.power_window()
    Obj2.power_break()
    Obj3 = DeluxCar('Honda','city')
    Obj3.info()
    Obj3.power_window()
    Obj3.power_break()
    

if __name__ == '__main__':
    Main()
In [ ]: