Sie sind auf Seite 1von 11

python

====
slice operator
built-in functions
filter, map, reduce
sys
pythonpath
math

Creating a python packages


local, nonlocal and global variables
flavours -- anaconda
inheritance, multiple inheritance, polymorphism, encapsulation, abstraction
cgi

django static
networking
command line arguments
property function

###########################################################################

Some Built-in functions:


===============
from math import *

pow(2,5)

########################

sqrt(16)

########################

abs(-4); abs(3+7j); sqrt(3*3+7*7)

########################

all([True,True,True]); all([1,1,1]); all([True,True,False]); all([1,1,0])

########################

any([True,True,True]); any([1,1,1]); any([True,False,False]); any([1,0,0])

########################

bin(192); int(0b11000000)

########################

bool(1); bool(0)

########################

chr(97); ord('a')

########################
x=5; id(x); hex(id(x))

########################

int(11.23); float(11); complex(3,5)

#Setting precision of floating point value


#=========================================
a = 4.1213243546799098; b = 6.9379830249390343; print("{0:0.2f}
\n{1:0.4f}".format(a,b))

########################

str(153)

########################

len(str(153))

########################

min(3,6,9)

########################

max(3,6,9)

########################

divmod(8,2); divmod(7,3)

### divmod(dividend,divisor) ### (quotient,remainder)

########################

x=3; isinstance(x,int); isinstance(x,float)

########################

x = input('Enter your name: '); print('Hello, ' + x)


Aravind

########################

# Use of join function to join list elements.


list1 = ['a','p','p','l', 'e']
print("".join(list1))

########################

list2 = ['Banana','Cherry','Dragon fruit']


print("\n".join(list2))

########################

list3 = ['1','2','3']
print("-".join(list3))
vowels = ['e','i','a','u','o']; vowels.sort(); print(vowels)
numbers = [1,3,4,2,5]; numbers.sort(); print(numbers)

vowels = ['e','i','a','u','o']; vowels.sort(reverse=True); print(vowels)


numbers = [1,3,4,2,5]; numbers.sort(reverse=True); print(numbers)

########################

for i,string in enumerate(['apple','banana','cherry']):


print("Index position ",i,"-->",string)

########################

iter() Function
------------------
mylist = ["apple", "banana", "cherry"]
x = iter(mylist)
print(next(x))
print(next(x))
print(next(x))

########################################################################

Creating a Python Package


======================
c:\>
mkdir my_package
echo # >> my_package\__init__.py

echo def greet(name): >> my_package\module1.py


echo print("Hello "+name) >> my_package\module1.py

echo def power(x,y): >> my_package\module2.py


echo return x**y >> my_package\module2.py

c:\>
python
>>>
from my_package.module1 import greet
from my_package.module2 import power

greet("Madan")
power(3,6)

###########################################################################
conda info
conda update conda

conda install django==2.2


conda update django
conda uninstall django
conda list
conda create --name myenv python=3.7
conda activate myenv
conda deactivate
conda env remove --name myenv
conda env list
conda info --envs
pip install <package>

###########################################################################

# Closures
# ========
# A Closure is a function object that remembers values in enclosing scopes
# even if they are not present in memory.
# msg is not defined inside function_A and it takes it from outside function_A.
# This is called enclosing scope.

msg = 'Welcome'
def function_A():
msg = 'Hi'
def function_B(): # Nested Funtion.
print (msg) # Enclosing Scope.
function_B()
print (msg)

function_A()
print(msg)
# output
# Hi
# Hi
# Welcome
############################################################################
msg = 'Welcome'
def function_A():
msg = 'Hi'
def function_B():
msg = 'Hello' # msg is a local variable
print (msg)
function_B()
print (msg)

function_A()
print(msg)
# output
# Hello
# Hi
# Welcome

############################################################################

msg = 'Welcome'
def function_A():
msg = 'Hi'
def function_B():
nonlocal msg # msg is defined as nonlocal variable
msg = 'Hello'
print (msg)
function_B()
print (msg)

function_A()
print(msg)
# output
# Hello
# Hello
# Welcome

############################################################################
msg = 'Welcome'
def function_A():
msg = 'Hi'
def function_B():
global msg # msg is defined as global variable
msg = 'Hello'
print (msg)
function_B()
print (msg)

function_A()
print(msg)
# output
# Hello
# Hi
# Hello

############################################################
Inheritance Syntax:
-------------------
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class

Example:
--------
$nano person.py
---------------------------------------------------------
class Person:
def __init__(self,fname,lname,age):
self.fname=fname
self.lname=lname
self.age=age
def get_name(self):
return self.fname+" "+self.lname

class Employee(Person):
def __init__(self,fname,lname,age,staffnum):
Person.__init__(self,fname,lname,age) #Keeps the parent's inheritance
self.staffnum=staffnum
def get_employee_details(self):
return self.get_name()+", "+str(self.age)+", "+str(self.staffnum)

x=Person("Praveen","G",50)
y=Employee("Naveen","B",30,2110)

print(x.get_name())
print(y.get_employee_details())
---------------------------------------------------------
Our program returns the following output:
$ python3 person.py
Praveen G
Naveen B, 30, 1007

=======================================================================
Multiple Inheritance
===============

##################################
class A:
def sayhi1():
print("A")

class B:
def sayhi2():
print("B")

class MI(A,B):
pass

MI.sayhi1()
MI.sayhi2()

##################################

class A:
def sayhi():
print("A")

class B:
def sayhi():
print("B")

class MI(A,B):
pass

MI.sayhi()

##################################
Multiple Inheritance -- Method Resolution Order (MRO)
==========================================
class X:
pass

class Y:
pass

class Z:
def sayhi():
print("Z")

class A(X,Y):
pass
class B(X,Z):
pass

class M(B,A,Z):
pass

M.sayhi()
M.mro()

################################

############################################################################
# Polymorphism

class India():
def capital(self):
print("New Delhi is the capital of India.")

def language(self):
print("Hindi the primary language of India.")

def category(self):
print("India is a developing country.")

class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")

def language(self):
print("English is the primary language of USA.")

def category(self):
print("USA is a developed country.")

obj_ind = India()
obj_usa = USA()

#Implement polymorphism with a for loop


#=========================
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.category()

#Implement polymorphism with a function


#=================================
def func(country):
country.capital()
country.language()
country.category()

func(obj_ind)
func(obj_usa)
#(Polymorphism with Inheritance) and Method Overriding
#=============================================
class Bird:
def intro(self):
print("There are many types of birds.")

def flight(self):
print("Most of the birds can fly but some cannot.")

class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")

class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

obj_bird.intro()
obj_bird.flight()

obj_spr.intro()
obj_spr.flight()

obj_ost.intro()
obj_ost.flight()

############################################################
############################################################
############################################################
# _single_leading_underscore
This convention is used for declaring private variables, functions, methods and
classes in a
module. Anything with this convention are ignored in from module import *
############################################################################
# __double_leading_underscore
# Python Encapsulation
# ==================
class Car:
__maxspeed = 0
__name = ""
def __init__(self):
self.__progressIndicator()
self.__maxspeed = 110
self.__name = "Lighting McQueen"
def drive(self):
print(str(self.__name)+' is speeding at ' + str(self.__maxspeed)+'KMPH')
def setMaxSpeed(self,speed):
self.__maxspeed = speed
def __progressIndicator(self):
print('Initialising car. Done !')
redcar = Car()
redcar.__progressIndicator() # This private method is not accesible from
object.

redcar.drive()

redcar.__maxspeed = 10 # This variable will not change as its a private


variable
redcar.__name = "Jackson Storm" # This variable will not change as its a
private variable

redcar.setMaxSpeed(220)
redcar.drive()

"""
# Encapsulation prevents us from accessing private variables and methods
accidentally.
but not intentionally.

# redcar._Car__progressIndicator()
# __progressIndicator() private method is accesible from the object by adding _Car
in the
begining.

# redcar._Car__maxspeed = 10
# redcar.drive()
"""
############################################################################
# Abstraction
#==========
from abc import ABC, abstractmethod
class ParentCTP(ABC): #Parent_Click_To_Pay
def print_slip(self, amount):
print('Purchase of amount- ', amount)
@abstractmethod
def payment(self, amount):
pass

class ChildCCP(ParentCTP): #Child_Credit_Card_Payment


def payment(self, amount):
print('Credit card payment of- ', amount)

class ChildMWP(ParentCTP):
#Child_Mobile_Wallet_Payment
def payment(self, amount):
print('Mobile wallet payment of- ', amount)

obj = ChildCCP()
obj.payment(100)
obj.print_slip(100)
print(isinstance(obj, ParentCTP))

obj = ChildMWP()
obj.payment(200)
obj.print_slip(200)
print(isinstance(obj, ParentCTP))
########################################################

#########################################
# Python program to explain property() function

# MyString class
class MyString:
def __init__(self, value):
self._value = value

# getting the values


def getValue(self):
print('Getting value : ')
return self._value

# setting the values


def setValue(self, value):
print('Setting value to : ' )
print(value)
self._value = value

# deleting the values


def delValue(self):
print('Deleting value')
del self._value

value = property(getValue, setValue, delValue, )

##################

obj = MyString('Python is easy to learn.') #


Instantiate an object

print(obj.value)
# getValue
obj.value = 'Python is a popular programming language.' # setValue
del obj.value
# delValue
#########################################
# Python program to explain property()
# function using decorator

class MyString:
def __init__(self, value):
self._value = value

# getting the values


@property
def value(self):
print('Getting value : ')
return self._value

# setting the values


@value.setter
def value(self, value):
print('Setting value to : ')
print(value)
self._value = value
# deleting the values
@value.deleter
def value(self):
print('Deleting value')
del self._value

##################

obj = MyString('Python is easy to learn.') #


Instantiate an object

print(obj.value)
# getValue
obj.value = 'Python is a popular programming language.' # setValue
del obj.value
# delValue
#########################################

########################################################