Friday, August 28, 2015

tool #2 - python

----------------------------------
1. Basic syntax
----------------------------------

--------------------------------
Variable    Description
--------------------------------
PYTHONPATH    It has a role similar to PATH. This variable tells the Python
                           interpreter where to locate the module files imported into
               a program. It should include the Python source library directory
               and the directories containing Python source code. It is
              sometimes preset by the Python installer.
PYTHONSTARTUP     It contains the path of an initialization file
               containing Python source code. It is executed every time you start
               the interpreter. It is named as .pythonrc.py in Unix and it
               contains commands that load utilities or modify PYTHONPATH.
PYTHONCASEOK    It is used in Windows to instruct Python to find the
               first case-insensitive match in an import statement. Set this variable
               to any value to activate it.
PYTHONHOME    It is an alternative module search path. It is usually
               embedded in the PYTHONSTARTUP or PYTHONPATH directories
               to make switching module libraries easy.

--------------------------------
Option    Description
--------------------------------
-d    provide debug output
-O    generate optimized bytecode (resulting in .pyo files)
-S    do not run import site to look for Python paths on startup
-v    verbose output (detailed trace on import statements)
-X    disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6
-c   cmd     run Python script sent in as cmd string
file      run Python script from given file

#!/usr/bin/python

print "Hello, Python!"

Lines and Indentation
 The number of spaces in the indentation is variable,
 but all statements within the block must be indented the same amount.

Eg:

if True:
    print "True"
else:
 print "False"


Multi-Line Statements : line continuation character (\)
Eg:
total = a + \
           b + \
           c

Quotation in Python
-   ' or " or '''
-   The triple quotes are used to span the string across multiple lines.

Eg:
word = 'word'
sentence = "This is a sentence."
paragraph = '''This is a paragraph. It is
made up of multiple lines and sentences.'''

Comments:  # blahblah....

Blank Lines : A line containing only whitespace, possibly with a comment.

Multiple Statements on a Single Line
Eg:
    import sys; x = 'foo'; sys.stdout.write(x + '\n')

Variable types:
- Python variables do not need explicit declaration to reserve
 memory space.
 The declaration happens automatically when you assign a value to a variable.
- Types:
    - numbers (int, long, flaot, complex)
    - string    
    - list :       [], element & size can be changed.
    - tuple:     (), element & size can not be updated once created,
                   read-only list.
    - dictionary : map

Eg:
# numbers
  a=100      # delcare variable a
  b=2.3
  c="xxx"
  a=b=c=1    # multple assignment
  del a, b       # undeclare variable a and b

# string
a="hello world "
print a,  a[0] , a[1], a[0:2]

# list
a=['s', 32, 2.3, 'dx', 32]
a[2]=100
print a, a[0:1], a[3:]

# tuple
a=('s', 32, 2.3, 'dx', 32)
a[2]=100  # invalid
print a, a[0:1], a[3:]

# dictionary
a={}                
a={2: 32, 'ab': 1}
a['ab']=1
a[2]=32
print a
print a.keys()
print a.values()

Type conversion:
int(x [,base]) / long(x [,base] ) / float(x) / complex(real [,imag]) / str(x) /
repr(x) / eval(str) / tuple(s) / list(s) / set(s) / dict(d) / frozenset(s) /
chr(x) / unichr(x) / ord(x) / hex(x) / oct(x)

----------------------------------
2. Operators
----------------------------------
Arithmetic operators:
+
-
*
/
%   # modulues (remainder)
//    # floor division ( integer part before decimal point)
**   # exponent

Eg:
9//2 => 4
9%2  >= 1
9**2 => 81

Comparison operators:
==
!=
<>    #  not equal, similar to !=
>
<
>=
<=

Assignment operators:
=
+=
-=
*=
/=
%=
**=
//=

Bitwise operators:
&     # AND : It copies a bit if it exists in both operands.
|      # OR  : It copies a bit if it exists in either operand.  (OR = AND + XOR)
^     # XOR : It copies a bit if it is set in one operand but NOT both.
~     # flip bits
<<  # left shift
>>  # right shift

Eg:
a=60    # 0011 1100
b=13    # 0000 1101

(a&b)
(a|b)
(a^b)
(~a)
a<<    ==> 240
a>>    ==> 15

Membership operators:
is
is not

Eg :
a=b=1 ;   a is b ;    a is not  b

----------------------------------
3. Statements
----------------------------------

if   expr :   statement

if   expr :  
   statement(s)
else:
   statement(s)

Eg:
if ( a==1 ): print "a is ", a

if ( a==1 ):
  print "a is ", 1
else:
  print "a is ", 2


while   expr:
  statement(s)

for   var   in   sequence:
  statements(s)

for   var   in   sequence:
  for var2   in   sequence:
      statements(s)
  statements(s)

while   expr:
  while   expr:
       statement(s)
  statement(s)

Eg:
for  a  in [1,2]:
  print a

Break : exit loop
for letter in 'Python':
  if letter == 'h':
     break
  print letter

Continue  : exit current iteration
for letter in 'Python':
  if letter == 'h':
     continue
  print letter

Pass : do nothing
for letter in 'Python':
  if letter == 'h':
     pass
  print 'Letter :', letter


----------------------------------
4. String
----------------------------------
4.1) String Special Operators

Eg:
a='Hello'
b='Python',

Operator    Description    Example
+       Concatenation -      a + b will give HelloPython
*        Repetition -            a*2 will give -HelloHello
[]       Slice -                    a[1] will give e
[:]    Range Slice -      a[1:4] will give ell
in      Membership -     H in a will give 1
not in     Membership -     M not in a will give 1
r or R     Raw String -  Suppresses actual meaning of Escape characters.
             The "r" can be lowercase (r) or uppercase (R) and
             must be placed immediately
               print r'\n'   --> prints \n
               print R'\n'  --> prints \n
u           Normal strings in Python are stored internally as 8-bit ASCII,
            while Unicode strings are stored as 16-bit Unicode.
            This allows for a more varied set of characters,
             including special characters from most languages in
             the world.    Eg:       print u'Hello, world!'
%           Format

4.2) String Formatting Operator
Eg:
print "name is   %s  and weight is %d   kg!"    %  ('deyong', 21)

output:
        name is deyong and weight is 21 kg!

Format Symbol    Conversion
%c     character
%s     string conversion via str() prior to formatting
%i     signed decimal integer
%d     signed decimal integer
%u     unsigned decimal integer
%o     octal integer
%x     hexadecimal integer (lowercase letters)
%X     hexadecimal integer (UPPERcase letters)
%e     exponential notation (with lowercase 'e')
%E     exponential notation (with UPPERcase 'E')
%f      floating point real number
%g      the shorter of %f and %e
%G     the shorter of %f and %E


Symbol    Functionality
**    argument specifies width or precision
-    left justification
+    display the sign
<sp>    leave a blank space before a positive number
#    add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X',
      depending on whether 'x' or 'X' were used.
0    pad from left with zeros (instead of spaces)
%    '%%' leaves you with a single literal '%'
(var)    mapping variable (dictionary arguments)
m.n.    m is the minimum total width and n is the number of digits
          to display after the decimal point (if appl.)

More details is here.


----------------------------------
5. Sequence
----------------------------------
Python is 0-based  for list and  tuple.

5.1) Basic List Operations
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];

list[2] = 2001;   # update
del list1[2];        # delete


Python Expression    Results     Description
len([1, 2, 3])    3    # Length
[1, 2, 3] + [4, 5, 6]    [1, 2, 3, 4, 5, 6]    # Concatenation
['Hi!'] * 4    ['Hi!', 'Hi!', 'Hi!', 'Hi!']        # Repetition
3 in [1, 2, 3]    True   #  Membership
for  x  in  [1, 2, 3]: print x     1 2 3   # Iteration

# Indexing, Slicing, and Matrixes

SN    Function with Description
1    cmp(list1, list2)  # Compares elements of both lists.
2    len(list)             # Gives the total length of the list.
3    max(list)            # Returns item from the list with max value.
4    min(list)            # Returns item from the list with min value.
5    list(seq)             # Converts a tuple into list.


SN    Methods with Description
1    aList.append(obj)         #Appends object obj to list
2    aList.count(obj)          #Returns count of how many times obj occurs in list
3    aList.extend(seq)        #Appends the contents of seq to list
4    aList.index(obj)          # Returns the lowest index in list that obj appears
5    aList.insert(index, obj) #Inserts object obj into list at offset index
6    aList.pop(obj=list[-1])  #Removes and returns last object or obj from list
7    aList.remove(obj)          #Removes object obj from list
8    aList.reverse()               #Reverses objects of list in place
9    aList.sort([func])          #Sorts objects of list, use compare func if given

5.2) tuple
-  A tuple is a sequence of immutable Python objects.
-  Tuples are sequences, just like lists.
-  The differences between tuples and lists are,
    the tuples cannot be changed unlike lists and
-  tuples use parentheses, whereas lists use square brackets.

Eg:tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

5.3) dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Age']: ", dict['Age']         # access element
dict['Age'] = 8;                               # update existing entry
dict['School'] = "DPS School"         # Add new entry
del dict['Name']                             # remove entry with key 'Name'
dict.clear()                                    # remove all entries in dict
del  dict                                         # delete entire dictionary

More details about dictionary is here.


5.4) date and time
tick : number of seconds since epoch (The function time.time()
        returns the current system time in ticks since 12:00am,
        January 1, 1970(epoch). )

more details about date and time is here.

----------------------------------
6. Function
----------------------------------
Syntax:
def f1( params ):
      "function_docstring"
      function_suite
      return   [expression]

All parameters (arguments) in the Python language are "passed by reference".

Eg:
#!/usr/bin/python

# Function definition is here
def   f1( mylist ):
    # mylist is still refered to the same reference in  
    # calling function.
    mylist.append([a,b]);     
    print "in function ", mylist
    return

def   f2( mylist ):
    #   mylist is referred to a NEWreference in function.
    #   while in calling function, mylist's reference remains the same.
    mylist = [1,2,3,4];            # new reference            
    print "in function ", mylist
   return

mylist=[1,2,3]
f1(mylist)
print " out function: " , mylist
mylist=[1,2,3]
f2(mylist)
print " outside function " , mylist

Output:
in functin: [1,2,3, [a,b] ]
out function: [1,2,3, [a,b] ]
in function: [1,2,3,4]
out function: [1,2,3]

6.1) Keyword arguments
They are related to the function calls (the moment when function gets called).
Benefits of using keyword when calling function:
-  the caller identifies the arguments by the parameter name.
-  could be placed out of order

Eg:
def   f1 ( name , age)
    ....
    ....

# call f1
f1("deyong", 44)     # required arguments ( normal style )
f1(name="deyong", age=44)    # keyword arguments
f1(age= 44, name="deyong")   # keyword arguments

6.2) Default argument
Eg:
def   f1 ( name , age=100)   # default value is set
    ....
    ....

f1(age=10, name="deyong")
f1(name="deyong" )       # age will be set as default value 100.

6.3) variable-length arguments
Syntax:
def   f1 ( [formal_args,]  * tuple_var_args ):
    "function_docstring"
    function_suite
    return [expression]

-  An asterisk (*) is placed before the variable name that holds the values
  of all non-keyword variable arguments.
-  This tuple remains empty if no additional arguments are specified during
  the function call.

Eg:
def   printinfo( arg1, *vartuple ):
  "This prints a variable passed arguments"
  print "Output is: "
  print arg1
  for var in vartuple:
     print var
  return;

# Now you can call printinfo function
printinfo( 10 )
printinfo( 10,  60, 50 )

Output is:
10
Output is:
10
60
50

6.4) anonymous function
- These functions are called anonymous because they are not declared
  in the standard manner by using the def keyword.
- You can use the "lambda" keyword to create small anonymous functions.

Syntax:

  lambda  [arg1 [,arg2,.....argn]]  :  expression

Eg:
# Function definition is here
# variable sum  becomes a function.
sum = lambda arg1, arg2 :  arg1 + arg2;   

# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print ( lambda  a , b : a+b ) ( 3, 5)

6.5) return statement
- The statement return [expression] exits a function, optionally passing back an
 expression to the caller.
-  A return statement with no arguments is the same as "return None".

# Global vs. Local variables
- Variables that are defined inside a function body have a local scope
-  local variables can be accessed only inside the function in which they are declared
- those defined outside function have a global scope.
- global variables can be accessed throughout the program body by all functions.

-----------------
7. Module
-----------------
- A module allows you to logically organize your Python code.
- Grouping related code into a module makes the code easier to understand and use.
- A module is a Python object with arbitrarily named attributes that you can bind and reference.
- The Python code for a module named "aname" normally resides in a file "aname.py". ( same name)

Syntax:
#1) import modules
import module1[, module2[,... moduleN]

#2)  import specific attributes from a module.
from   modname   import    name1[, name2[, ... nameN]]  
from   modname   import   *      # alternative of  "import modnmae"

Locate modules:
- current directory
- directories defined in PYTHONPATH
- default path: for instance, /usr/local/lib/python on unix

Namespaces and Scoping
- Variables are names (identifiers) that map to objects.
- A namespace is a dictionary of variable names (keys) and their corresponding objects (values).
- The statement global VarName tells Python that VarName is a global variable.

Eg:
Money = 2000
def AddMoney():
    global Money
    Money = Money + 1

print Money
AddMoney()
print Money

The dir( ) Function
Returns a sorted list of strings containing the names defined by a module.

The globals() and locals() Functions −
Return the names in the global and local namespaces depending on the location from where they are called.

The reload() Function
-  When the module is imported into a script, the code in the top-level portion of a module is executed only once.
-  Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this −

Packages in Python
-  a hierarchical "file directory structure" that defines a single Python application
environment that consists of modules and subpackages and sub-subpackages, and so on.

Eg:
pkg1  is the name of a directory.
pkg1/__init__.py     #  containing alll the modules under directory pkg1.
pkg1/mod1.py
pkg1/mod2.py
pkg1/mod3.py

# Content of  pkg1/__init__.py
from mod1 import mod1
from mod2 import mod2
from mod3 import mod3

# Content of pkg1/mod1.py
def   mod1():
    print " mod 1"

# Code to import package pkg1.
import   pkg1

pgk1.mod1()
pgk1.mod2()
pgk1.mod3()

-----------------
8. File I/O
-----------------
# Print to screen
print "xxx" , a, b

# Read from keyboard
str = raw_input("Enter your input: ");
print "Received input is : ", str

The input([prompt]) function is equivalent to raw_input, except that it assumes
the input is a valid Python expression and returns the evaluated result to you.

Eg:
str = input("Enter your input: ");
print "Received input is : ", str

Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is :  [10, 20, 30, 40]

# open file
file object = open(file_name [, access_mode][, buffering])

The file Object Attributes
Once a file is opened and you have one file object, you can get various information related to that file.

Here is a list of all attributes related to file object:
Attribute    Description
file.closed    Returns true if file is closed, false otherwise.
file.mode    Returns access mode with which file was opened.
file.name    Returns name of the file.
file.softspace    Returns false if space explicitly required with print, true otherwise.

#  Reading and Writing Files
The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files.

Syntax
fileObject.read([count]);
    Here, passed parameter is the number of bytes to be read from the opened file.
    This method starts reading from the beginning of the file and if count is missing,
     then it tries to read as much as possible, maybe until the end of file.

fileObject.write(string);

# read file
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
fo.close()

# write to file         
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
fo.close()

File Positions
The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file.

The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved.

Renaming and Deleting Files
Syntax
os.rename(current_file_name, new_file_name)
os.remove(file_name)

Directories in Python
Syntax
os.mkdir("newdir")

chdir()   -- to change the current directory.
Syntax
os.chdir("newdir")

getcwd()  -  displays the current working directory.
Syntax
os.getcwd()

rmdir()   -  deletes the directory, which is passed as an argument in the method.
Syntax:
os.rmdir('dirname')

---------------------
9. Exception
---------------------
-  Python provides two very important features to handle any unexpected error in your
Python programs and to add debugging capabilities in them:
- Exception handling
- Assertions

Assertions in Python
An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program.
The assert Statement
-  If the expression is true, nothing happens.
-  If the expression is false, Python raises an AssertionError exception.
The syntax
assert Expression[, Arguments]

Eg:
#!/usr/bin/python
def   KelvinToFahrenheit(Temperature):
    assert (Temperature >= 0),"Colder than absolute zero!"
    return ((Temperature-273)*1.8)+32

print   KelvinToFahrenheit(273)
print   int(KelvinToFahrenheit(505.78))
print   KelvinToFahrenheit(-5)

# exception
Syntax
try....except...else blocks −

try:
  You do your operations here;
  ......................
except Exception_I:
    If there is ExceptionI, then execute this block.
except Exception_II:
    If there is ExceptionII, then execute this block.
    ......................
else:
    If there is no exception then execute this block.

Eg:
try:
  fh = open("testfile", "w")
  fh.write("This is my test file for exception handling!!")
except IOError:
  print "Error: can\'t find file or read data"
else:
  print "Written content in the file successfully"
  fh.close()




The except Clause with Multiple Exceptions
You can also use the same except statement to handle multiple exceptions as follows −

try:
    You do your operations here;
    ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
    If there is any exception from the given exception list,
    then execute this block.
    ......................
else:
    If there is no exception then execute this block.


The try-finally Clause
The finally block is a place to put any code that must execute, whether the try-block raised an exception or not.
Syntax
try:
    You do your operations here;
    ......................
    Due to any exception, this may be skipped.
finally:
    This would always be executed.
     ......................

Argument of an Exception
An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows −

try:
    You do your operations here;
    ......................
except ExceptionType, Argument:
    You can print value of Argument here...

Raising an Exceptions
Syntax
raise [Exception [, args [, traceback]]]

Eg:
def    functionName( level ):
    if level < 1:
       raise "Invalid level!", level        #  <=== name of exception  "Invalid level"
       # The code below to this would not be executed
       # if we raise the exception
try:
   Business Logic here...
except "Invalid level!":              # <===   "Invalid level" exception.
   Exception handling here...
else:
   Rest of the code here...


User-Defined Exceptions
-  create your own exceptions by deriving classes from the standard built-in exceptions.

Eg:
# a class is created that is subclassed from RuntimeError.
class Networkerror(RuntimeError):
  def __init__(self, arg):
     self.args = arg

try:
    raise Networkerror("Bad hostname")
except Networkerror,e:
    print e.args

----------------------------------
10. Class
----------------------------------
Class variable: -- static variable, shared by all instances of a class.  
Instance variable: A variable of the current instance.
Data member:   class variables +  instance variables
Instantiation: The creation of an instance of a class.
Method : member function
Object:  an instance.   data members + functions.
Function overloading:  more than one behavior to a particular function ( argument type change, umber of arguments)
Operator overloading: The assignment of more than one function to a particular operator.

10.1)  Create class

Syntax:
class ClassName:
    'Optional class documentation string'
    class_suite

Eg:
class Employee:
    'Common base class for all employees'
    empCount = 0     # class variable / static variable

    def __init__(self, name, salary):
         self.name = name         # instance variable
         self.salary = salary
         Employee.empCount += 1
  
  def   displayCount(self):
      print "Total Employee %d" % Employee.empCount

  def displayEmployee(self):
     print "Name : ", self.name,  ", Salary: ", self.salary

10.2)  Create instance
emp1 = Employee("Zara", 2000)
# Access attributes
emp1.displayEmployee()
print "Total Employee %d"   % Employee.empCount

Instead of using the normal statements to access attributes, you can use the following functions −
(DXU:  No need to write set and get functions anymore. )
The getattr(obj, name[, default]) : to access the attribute of object.
The hasattr(obj,name) : to check if an attribute exists or not.
The setattr(obj,name,value) : to set an attribute. If attribute does not exist, then it would be created.
The delattr(obj, name) : to delete an attribute.

Eg:
hasattr(emp1, 'age')     # Returns true if 'age' attribute exists
getattr(emp1, 'age')      # Returns value of 'age' attribute
setattr(emp1, 'age', 8)   # Set attribute 'age' at 8
delattr(empl, 'age')        # Delete attribute 'age'

Built-In Class Attributes

Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute −
__dict__:  Dictionary containing the class's namespace.
__doc__:  Class documentation string or none, if undefined.
__name__:  Class name.
__module__:   Module name in which the class is defined. This attribute is "__main__" in interactive mode.
__bases__:   A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.

Eg:
class Employee:
  'Common base class for all employees'
  empCount = 0

  def __init__(self, name, salary):
     self.name = name
     self.salary = salary
     Employee.empCount += 1
  
  def displayCount(self):
    print "Total Employee %d" % Employee.empCount

  def displayEmployee(self):
     print "Name : ", self.name,  ", Salary: ", self.salary

print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__

Output:
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}

10.3)  Destroying Objects (Garbage Collection)
-   Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space.
-  The process by which Python periodically reclaims blocks of memory that no longer are in use is termed Garbage Collection.
-  Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes.
-  An object's reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary).
-  The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically.

Eg:
# Increase ref. count  of <40>
a = 40      # Create object <40>
b = a       
c = [b]     
# Decrease ref. count  of <40>
del a        
b = 100     
c[0] = -1    

Eg2:
class Point:
   def __init( self, x=0, y=0):
       self.x = x
       self.y = y
   def __del__(self):
       class_name = self.__class__.__name__
       print   class_name,   "destroyed"

pt1 = Point()
pt2 = pt1
pt3 = pt1
print   id(pt1),   id(pt2),    id(pt3)      # prints the ids of the obejcts
del pt1
del pt2
del pt3

Class Inheritance
Syntax
class    SubClassName ( ParentClass1[,  ParentClass2, ...]):
    'Optional class documentation string'
    class_suite

Eg:
#!/usr/bin/python
class Parent:        # define parent class
  parentAttr = 100
  def __init__(self):
     print "Calling parent constructor"

  def parentMethod(self):
     print 'Calling parent method'

  def setAttr(self, attr):
     Parent.parentAttr = attr

  def getAttr(self):
     print "Parent attribute :", Parent.parentAttr
class Child(Parent): # define child class
  def __init__(self):
     print "Calling child constructor"

  def childMethod(self):
     print 'Calling child method'

c = Child()          # instance of child
c.childMethod()      # child calls its method
c.parentMethod()     # calls parent's method
c.setAttr(200)       # again call parent's method
c.getAttr()          # again call parent's method

10.4)  Overriding Methods
Eg:
#!/usr/bin/python
class Parent:        # define parent class
  def myMethod(self):
     print 'Calling parent method'

class Child(Parent): # define child class
  def myMethod(self):
     print 'Calling child method'

c = Child()          # instance of child
c.myMethod()         # child calls overridden method


# Base Overloading Methods
Following table lists some generic functionality that you can override in your own classes
SN    Method, Description & Sample Call
1    __init__ ( self [,args...] )  Constructor (with any optional arguments)
                                   eg : obj = className(args)
2    __del__( self )       Destructor, deletes an object
                                   eg : del obj
3    __repr__( self )    Evaluatable string representation
                                  eg : repr(obj)
4    __str__( self )     Printable string representation
                                 eg : str(obj)
5    __cmp__ ( self, x )     Object comparison
                                  eg : cmp(obj, x)

10.5)  Overloading Operators
Eg:
#!/usr/bin/python
class Vector:
  def __init__(self, a, b):
     self.a = a
     self.b = b

  def __str__(self):
     return 'Vector (%d, %d)' % (self.a, self.b)
  
  def __add__(self,other):
     return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print    v1 + v2
__str__      # print
__add__    #  a+b
__radd__   # b+a
__sub__    #  a-b
__div__      # a / b


10.6)  Data Hiding
An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then are not be directly visible to outsiders.
Eg:
#!/usr/bin/python
class   JustCounter:
  __secretCount = 0
  def count(self):
     self.__secretCount += 1
     print self.__secretCount

counter = JustCounter()
counter.count()
counter.count()
print   counter.__secretCount        # error

When the above code is executed, it produces the following result −

1
2
Traceback (most recent call last):
 File "test.py", line 12, in <module>
    print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'

Python protects those members by internally changing the name to include the class name. You can access such attributes as   object._className__attrName. If you would replace your last line as following, then it works for you −

.........................
print counter._JustCounter__secretCount

When the above code is executed, it produces the following result −

1
2
2

No comments:

Post a Comment