파이썬정리 20160130

349
PYTHON 이이이이 Moon Yong Joon

Upload: yong-joon-moon

Post on 21-Apr-2017

3.591 views

Category:

Data & Analytics


0 download

TRANSCRIPT

PowerPoint

Python Moon Yong Joon

Data(Object) Type

Data(Object) Type

Values and data types: >>> type(1.1) >> #string >>> if v.isdigit() :... s = int(v)... else :... s = 0... >>> s1

Numeric Type

Numberic Typesintfloatlongcomplex>>> id(1)5939944>>> v = 1>>> type(v)

>>> id(v)5939944>>> 1 context id

- , operatorOperationResultNotesx+ysum ofxandyx-ydifference ofxandyx*yproduct ofxandyx/yquotient ofxandyx//y(floored) quotient ofxandyx%yremainder ofx/y-xxnegated+xxunchangedabs(x)absolute value or magnitude ofxint(x)xconverted to integerlong(x)xconverted to long integerfloat(x)xconverted to floating pointcomplex(re,im)a complex number with real partre, imaginary partim.imdefaults to zero.c.conjugate()conjugate of the complex numbercdivmod(x,y)the pair(x//y,x%y)pow(x,y)xto the poweryx**yxto the powery

Sequence Type

Sequence Sequenec TypesString/unicodeBuffer/rangeList/tuplecontainercontainer** string

Elements

Sequence - Sequence , operatorOperationResultNotesxinsTrueif an item ofsis equal tox, elseFalsexnot insFalseif an item ofsis equal tox, elseTrues+tthe concatenation ofsandts*n,n*snshallow copies ofsconcatenateds[i]i'th item ofs, origin 0s[i:j]slice ofsfromitojs[i:j:k]slice ofsfromitojwith stepklen(s)length ofsmin(s)smallest item ofsmax(s)largest item ofs

Sequence-Accessing ValuesSequence Type(String, List, Tuple) [index] Sequence Instance index >>> l = [0,1,2,3]>>> l[0]0>>> s = "string">>> s[0]'s'>>> t = (0,1,2,3)>>> t[0]0>>>

Sequence-Updating Values Sequence Instance index . , Mutable List >>> l[0, 1, 2, 3]>>> l[0] = 100>>> l[100, 1, 2, 3]>>> t(0, 1, 2, 3)>>> t[0] = 100Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment>>> >>> s'string'>>> >>> s[0] = 'a'Traceback (most recent call last): File "", line 1, in TypeError: 'str' object does not support item assignmentList typeTuple typeString type

Sequence- Sequence sorted, reversed, enumerate, zip >>> for i, v in enumerate(['tic', 'tac', 'toe']):... print i, v ... 0 tic1 tac 2 toe >>> l1 = [1,2,3,4]>>> la = ['a','b','c','d']>>> for k,v in zip(l1,la) :... print k, v... 1 a2 b3 c4 d>>> >>> for i in reversed(xrange(1,10,2)): ... print i ... 9 7 5 3 1>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print f... apple banana orange pearenumerate()zip()reversed()sorted()

Sequence : Slice

Sequence slicing Sequence (string, list, tuple) slicing

[ ::]

>>> mystring[0:5] 'hello'>>> mystring[6:-1] 'worl'

Sequence slicing- >>> s = 'hello'>>> s[-3:]'llo'>>> s[:-3]'he'>>> s[-1:-3]''>>> s[-1:0]''>>> s[-1:-3:-1]'ol'>>>

[::]

Sequence : String Type

Sequence-Updating StringString update String Instance >>> s'string'>>> id(s)6122176>>> v = "updating " + s>>> id(v)106043176>>> v'updating string'>>> >>> s'string'>>>

String-operatorOperatorDescriptionExample+Concatenation - Adds values on either side of the operatora + b will give HelloPython*Repetition - Creates new strings, concatenating multiple copies of the same stringa*2 will give -HelloHello[]Slice - Gives the character from the given indexa[1] will give e[ : ]Range Slice - Gives the characters from the given rangea[1:4] will give ellinMembership - Returns true if a character exists in the given stringH in a will give 1not inMembership - Returns true if a character does not exist in the given stringM not in a will give 1r/RRaw String - Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter "r," which precedes the quotation marks. The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark.print r'\n' prints \n and print R'\n'prints \n%Format - Performs String formattingSee at next section

Sequence-String (1)String Method Descriptioncapitalize()Capitalizes first letter of stringcenter(width, fillchar)Returns a space-padded string with the original string centered to a total of width columns.count(str, beg= 0,end=len(string))Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.decode(encoding='UTF-8',errors='strict')Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.encode(encoding='UTF-8',errors='strict')Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.endswith(suffix, beg=0, end=len(string))Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.expandtabs(tabsize=8) Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.

Sequence-String (2)String Method Descriptionfind(str, beg=0 end=len(string))Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.index(str, beg=0, end=len(string))Same as find(), but raises an exception if str not found.isalnum()Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.isalpha()Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.isdigit()Returns true if string contains only digits and false otherwise.islower()Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.isnumeric()Returns true if a unicode string contains only numeric characters and false otherwise.

Sequence-String (3)String Method Descriptionisspace()Returns true if string contains only whitespace characters and false otherwise.istitle()Returns true if string is properly "titlecased" and false otherwise.isupper()Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.join(seq)Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.len(string)Returns the length of the stringljust(width[, fillchar])Returns a space-padded string with the original string left-justified to a total of width columns.lower()Converts all uppercase letters in string to lowercase.lstrip()Removes all leading whitespace in string.maketrans()Returns a translation table to be used in translate function.

Sequence-String (4)String Method Descriptionmax(str)Returns the max alphabetical character from the string str.min(str)Returns the min alphabetical character from the string str.replace(old, new [, max])Replaces all occurrences of old in string with new or at most max occurrences if max given.rfind(str, beg=0,end=len(string))Same as find(), but search backwards in string.rindex( str, beg=0, end=len(string))Same as index(), but search backwards in string.rjust(width,[, fillchar])Returns a space-padded string with the original string right-justified to a total of width columns.rstrip()Removes all trailing whitespace of string.split(str="", num=string.count(str))Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.splitlines( num=string.count('\n'))Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.

Sequence-String (5)String Method Descriptionstartswith(str, beg=0,end=len(string))Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.strip([chars])Performs both lstrip() and rstrip() on stringswapcase()Inverts case for all letters in string.title()Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.translate(table, deletechars="")Translates string according to translation table str(256 chars), removing those in the del string.upper()Converts lowercase letters in string to uppercase.zfill (width)Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).isdecimal()Returns true if a unicode string contains only decimal characters and false otherwise.

String-escape Backslash notationHexadecimal characterDescription\a0x07Bell or alert\b0x08Backspace\000\cxControl-x\C-xControl-x\e0x1bEscape\f0x0cFormfeed\M-\C-xMeta-Control-x\n0x0aNewline (Line Feed) \nnnOctal notation, where n is in the range 0.7\r0x0dCarriage return \s0x20Space\t0x09Tab\v0x0bVertical tab\xCharacter x\xnnHexadecimal notation, where n is in the range 0.9, a.f, or A.F\\ "\"\' (')\" (")

Sequence : List Type

Sequence - List List

Python ExpressionResultsDescriptionl=[1,2,3] l.append(4)[1, 2, 3, 4] del l[3][1, 2, 3] len([1, 2, 3])3Length [1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6] Concatenation['Hi!'] * 4['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition3 in [1, 2, 3]True Membershipfor x in [1, 2, 3]: print x,1 2 3 - Iteration

Sequence-List Function Descriptioncmp(list1, list2)Compares elements of both lists.len(list)Gives the total length of the list.max(list)Returns item from the list with max value.min(list)Returns item from the list with min value.list(seq)Converts a tuple into list.str(list)Produces a printable string representation of a listtype(list)Returns the type of the passed variable. If passed variable is list, then it would return a list type.

Sequence-List class list class object >>> list

>>> id(list)505560280>>> >>> >>> l1 = list()>>> id(l1)106593376>>> isinstance(l1,list)True>>>

list isinstance

Sequence-List Method Descriptionlist.append(obj)Appends object obj to listlist.count(obj)Returns count of how many times obj occurs in listlist.extend(seq)Appends the contents of seq to listlist.index(obj)Returns the lowest index in list that obj appearslist.insert(index,obj)Inserts object obj into list at offset indexlist.pop(obj=list[-1])Removes and returns last object or obj from listlist.remove(obj)Removes object obj from listlist.reverse()Reverses objects of list in placelist.sort([func])Sorts objects of list, use compare func if given

Sequence-List Comprehension

A = [ for i in sequence if ]

>>> squares = [] >>> for x in (10): ... squares.append(x**2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> squares = [x**2 for x in range(10)]>>> squares[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]>>>

Sequence-List stack Stack LIFO(last in first out) List (append) (pop)

>>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6]>>> stack.pop()6 >>> stack.pop()5 >>> stack [3, 4]

Sequence-List queue queue FIFO(first in first out) List (append) (reverse,pop)

>>> l = [1,2,3,4]>>> l.reverse()>>> l[4, 3, 2, 1]>>> l.pop()1>>> l.reverse()>>> l[2, 3, 4]>>>

Sequence : Tuple Type

Sequence - Tuple tuple immutable Slicing String

Python ExpressionResultsDescriptionT =(1,)(1,) (,) T = (1,2,3,4)(1, 2, 3, 4) len((1, 2, 3))3Length (1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6) Concatenation('Hi!) * 4'Hi!Hi!Hi!Hi!' string 3 in (1, 2, 3)True Membershipfor x in (1, 2, 3): print x,1 2 3 - Iteration

Sequence- Tuple tuple Function Descriptioncmp(tuple1, tuple2)Compares elements of both tuples.len(tuple)Gives the total length of the tuple.max(tuple)Returns item from the tuple with max value.min(tuple)Returns item from the tuple with min value.tuple(seq)Converts a list into a tuple.str(tuple)Produces a printable string representation of a tupletype(tuple)Returns the type of the passed variable. If passed variable is tuple, then it would return a tuple type.

Set Type

Set , (unordered)(&), (|), (-)

Set: mutable setFrozenset: immutable set

Set Set() 1 . mutable . >>> s = set([1],[2])Traceback (most recent call last): File "", line 1, in TypeError: set expected at most 1 arguments, got 2>>> s = set(([1],[2]))Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list'>>> >>> s = set(((1),(2)))>>> sset([1, 2])>>> >>> s = set({'a':1})>>> sset(['a'])

Set

Set dictionary immutable

Set Set Set type mutable

>>> >>> s = set([1,2,3])>>> sset([1, 2, 3])>>> s1 = set([1,2,3,3,4,4])>>> s1set([1, 2, 3, 4])>>> s.add(5)>>> sset([1, 2, 3, 5])>>> s1.add(5)>>> s1set([1, 2, 3, 4, 5])>>>

Set FrozenSet FrozenSet type immutable

>>> s = frozenset([1,2,3])>>> sfrozenset([1, 2, 3])>>> s.add(4)Traceback (most recent call last): File "", line 1, in AttributeError: 'frozenset' object has no attribute 'add'>>>

Set - OperationEquivalentResultlen(s)cardinality of setsxinstestxfor membership insxnot instestxfor non-membership inss.issubset(t)s=ttest whether every element intis inss.union(t)s|tnew set with elements from bothsandts.intersection(t)s&tnew set with elements common tosandts.difference(t)s-tnew set with elements insbut not ints.symmetric_difference(t)s^tnew set with elements in eithersortbut not boths.copy()new set with a shallow copy ofs

Set - set OperationEquivalentResults.update(t)s|=tupdate sets, adding elements fromts.intersection_update(t)s&=tupdate sets, keeping only elements found in bothsandts.difference_update(t)s-=tupdate sets, removing elements found ints.symmetric_difference_update(t)s^=tupdate sets, keeping only elements found in eithersortbut not in boths.add(x)add elementxto setss.remove(x)removexfrom sets; raises KeyError if not presents.discard(x)removesxfrom setsif presents.pop()remove and return an arbitrary element froms; raisesKeyErrorif emptys.clear()remove all elements from sets

Map Type

Map -dictionary Key/Value containerName 1Name 2container::Dictionary Type

Map - Accessing Elements Key/Value Key >>> dd = {'name': 'dahl', 'age':50}>>> dd{'age': 50, 'name': 'dahl'}>>> dd['name']'dahl'>>>

Map - Updating Elements Dictionary key key >>> dd = {'name': 'dahl', 'age':50}>>> dd{'age': 50, 'name': 'dahl'}>>> dd['name']'dahl'>>>>>> dd['sex'] ='male'>>> dd{'age': 50, 'name': 'dahl', 'sex': 'male'}>>> >>> dd['name'] = 'dahl moon'>>> dd{'age': 50, 'name': 'dahl moon', 'sex': 'male'}>>>

key : key :

Map - Delete Elements Dictionary , , dictionary instance >>> dd{'age': 50, 'name': 'dahl moon', 'sex': 'male'}>>> del dd['sex']>>> dd{'age': 50, 'name': 'dahl moon'}>>> >>> dd.clear()>>> dd{}>>> del dd>>> ddTraceback (most recent call last): File "", line 1, in NameError: name 'dd' is not defined>>>

Dict

Map dict Dictionary , , dictionary instance Function Descriptioncmp(dict1, dict2)Compares elements of both dict.len(dict)Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.str(dict)Produces a printable string representation of a dictionarytype(dict)Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.dict(mapping)Converts a map into list.

Map -dict class dict class object >>> dict

>>> id(dict)505532280>>>>>> d1 = dict()>>> id(d1)105140272>>> isinstance(d1,dict)True>>>

Dict isinstance

Map -dictionary Method Descriptiondict.clear()Removes all elements of dictionarydictdict.copy()Returns a shallow copy of dictionarydictdict.fromkeys()Create a new dictionary with keys from seq and valuessettovalue.dict.get(key, default=None)Forkeykey, returns value or default if key not in dictionarydict.has_key(key)Returnstrueif key in dictionarydict,falseotherwisedict.items()Returns a list ofdict's (key, value) tuple pairsdict.keys()Returns list of dictionary dict's keysdict.setdefault(key, default=None)Similar to get(), but will set dict[key]=default ifkeyis not already in dictdict.update(dict2)Adds dictionarydict2's key-values pairs todictdict.values()Returns list of dictionarydict's values

Boolean type & None

Boolean true/false or "python"""[1, 2, 3][](){}10None

If : passElse : pass

None (Not Exists) (Not Assigned, Not Defined) (No Value)(Initialized Value)

String Format

String Format ()

String-format index { } .format() 0 >>> " {0} {1} ".format(1,2,3)' 1 2 '>>> " {0} {1} {2} {3} ".format(1,2,3)Traceback (most recent call last): File "", line 1, in IndexError: tuple index out of range>>> {} {]

String-format name { } .format(=,)>>> "{first} {second} ".format(first=1, second=2)'1 2 '>>> {} {]

String-format {} { } .format(, =)>>> "{0} {second} ".format(1, second=2)'1 2 '>>> Key/Value

String-format {: [][] } .format()< : >: ^: >>> " left: {0:10} centre:{2:^10} ".format('hi', 'world', '!')' left: hi right: world centre: ! '>>> >>> "{0:=^10}".format("hi") '====hi====' >>> "{0:!> = 15 (means 0000 1111)

OperatorDescriptionExampleand Logical ANDIf both the operands are true then condition becomes true.(a and b) is true.or Logical ORIf any of the two operands are non-zero then condition becomes true.(a or b) is true.not Logical NOTUsed to reverse the logical state of its operand.Not(a and b) is false.

- OperatorDescriptionExample&Logical AND >>>s ='abc' >>>(len(s) == 3) & s.isalpha()True>>> (len(s) == 4) & s.isalpha()False>>> |Logical OR >>> (len(s) == 3) | s.isdigit()True

>>> (len(s) == 4) | s.isdigit()False>>>

&, | & : | : >>> (10+1) & 00>>> (10+1) | 011>>> 0 |1010>>>

OperatorDescriptionExampleinEvaluates to true if it finds a variable in the specified sequence and false otherwise.x in y, here in results in a 1 if x is a member of sequence y.not inEvaluates to true if it does not finds a variable in the specified sequence and false otherwise.x not in y, here not in results in a 1 if x is not a member of sequence y.

OperatorDescriptionExampleisEvaluates to true if the variables on either side of the operator point to the same object and false otherwise.x is y, hereisresults in 1 if id(x) equals id(y).is notEvaluates to false if the variables on either side of the operator point to the same object and true otherwise.x is not y, hereis notresults in 1 if id(x) is not

OperatorDescription**Exponentiation (raise to the power)~ + -Ccomplement, unary plus and minus (method names for the last two are +@ and -@)* / % //Multiply, divide, modulo and floor division+ -Addition and subtraction>> =Comparison operators == !=Equality operators= %= /= //= -= += *= **=Assignment operatorsis is notIdentity operatorsin not inMembership operatorsnot or andLogical operators

Python

: , ,,,

Private Private ,

(\) : : intention : (\n) (#) : Doc : single ('), double (") and triple (''' or """) quotes .__doc__ (;) : ;

- doc >>> import doctesthello world >>> doctest.__doc__'\nCreated on Fri Jan 08 14:46:31 2016\n\n@author: 06411\n'>>> # doctest.py # -*- coding: utf-8 -*-"""Created on Fri Jan 08 14:46:31 2016

@author: 06411"""

print("hello world ")

Variable

(Variable) ,

Variable ,

Variable = ()

Variable binding() Scope I + 1 I I NameError: name 'i' is not defined I = I + 1>>> message = "What's up, Doc?">>> n = 17>>> pi = 3.14159 ( ) .

Assignment & Type inference I = 1l = stringl = 1.1l . .

.

Variable Context .del , del() >>> a= 1>>> b =1>>> a1>>> b1>>> del a>>> del(b)>>> aTraceback (most recent call last): File "", line 1, in NameError: name 'a' is not defined>>> bTraceback (most recent call last): File "", line 1, in NameError: name 'b' is not defined>>>

Building Block

Building blockExpressionFunctionObjectVariable : point to objectCommand

ExpressionAn expression is a combination of values, variables, and operators. >>> (i for i in l)

>>> dir((i for i in l))['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw']>>>

: . Local > Global > Built-in

Locals() globals()

>>> p = 100>>> >>> def add(x,y) : p =0 print(locals())>>> globals()>>>

Variable Bound/unbound Binding >>> i =0>>> i = i + 1>>> i1>>>I = I + 1Traceback (most recent call last): File "", line 1, in NameError: name 'i' is not defined I + 1 Unbinding (NameError: name 'i' is not defined)

Namespace

Namespace , , name .

, , name , , ,

Namespace Import

pythonpath .

Namespace Dir() : , List

__dict__ : >>>dir() >>>dir()>>>.__dict__>>>

Object Namespace Base classclassinstanceinstanceinstance Dict{}Dict{}Dict{}Dict{}Dict{}

Namespace Namespace

function Namespace

Namespace Namespace .

Namespace .

locals()/globals() Dict{}Dict{}Dict{}Dict{}Dict{}Built-inDict{}

Namespace / -

Control flow

StatementStatementDescriptionif statements true if...else statements true if false else nested if statementsIf elif true false else

For Statement for in (sequence )

For else

Loop StatementLoop TypeDescriptionwhile loop true for loop sequence nested loops

With Statement with ,

f = open("foo.txt", 'w')f.write("Life is too short, you need python")f.close()with open("foo.txt", "w") as f: f.write("Life is too short, you need python")With file close

Break Statement control flow

for x in range(0, 5):print(x)if(x == 6):breakelse:print("else")

Continue Statement control flow

>>> for i in [1,2,3,4,5] :... if i == 2 :... continue... print i... 1345

Pass Statement pass Continue pass >>> for i in [1,2,3,4,5] :... if i == 2 :... pass... print i... 12345

else StatementFor/while else .If than else else

>>> if [1]: ... print("Then")... else: ... print("Else") Then >>>>>> for x in [1]: ... print("Then") ... else: ... print("Else") ... Then Else

Module/package

,

.

(.)

# mod.py

def apple(): print "I AM APPLES!" # this is just a variable

tangerine = "Living reflection of a dream" # mod_import.py

import modmod.apple() print mod.tangerine"

namespace .

Namespace : .__dict__ : .__dict__.get()

# mod.py

def apple(): print "I AM APPLES!" # this is just a variable

tangerine = "Living reflection of a dream" # mod_import.py

import mod

mod.__dict__.get(apple) mod.__dict__.get(tangerine )

namespace .

Namespace : .__dict__ : .__dict__.get()

# mod.py

def apple(): print "I AM APPLES!" # this is just a variable

tangerine = "Living reflection of a dream" # mod_import.py

import mod

mod.__dict__.get(apple) mod.__dict__.get(tangerine )

if __name__ == "__main__": Command __name__ __main__

Command __main__

command line __name__ __main__ import

if __name__ == "__main__": # print(safe_sum('a', 1)) print(safe_sum(1, 4)) print(sum(10, 10.4))else : # import

import # c:\python# mod1.py def sum(a, b): return a + b

c:\python>dir ... 2014-09-23 01:53 49 mod1.py ...# c:\python# import mod1

mod1.sum(10,10) # 20 import .

Module Module import

(Packages) ('.') ( )

import game.sound.echo # .. from game.sound import echofrom game.sound.echo import echo_test # ..

import .echo # importimport ..echo # import

game/ __init__.py # sound/ __init__.py echo.py wav.py graphic/ __init__.py screen.py render.py play/ __init__.py run.py test.py

(1)

1. Kakao pythonpath 2. account 3. account account.py

(2)1. myproject pythonpath 2. add_test.py 3. account.account import

:pythonpath pythonpath

set PYTHONPATH=c:\python20\lib;

: ide path .

#path>>> import sys>>> sys.path ['', 'C:\\Windows\\SYSTEM32\\python34.zip', 'c:\\Python34\\DLLs', 'c:\\Python34\\lib', 'c:\\Python34', 'c:\\Python34\\lib\\site-packages']

# >>> sys.path.append("C:/Python/Mymodules") >>> sys.path ['', 'C:\\Windows\\SYSTEM32\\python34.zip', 'c:\\Python34\\DLLs', 'c:\\Python34\\lib', 'c:\\Python34', 'c:\\Python34\\lib\\site-packages', 'C:/Python/Mymodules'] >>>

>>> import mod2 >>> print(mod2.sum(3,4)) # 7

Function

Function

()

# def () (:)

# () ()

>>> def add(x,y) :... return x+y... >>> # >>> add.func_code.co_varnames('x', 'y')>>> >>> # bytecode >>> add.func_code.co_code'|\x00\x00|\x01\x00\x17S'>>>

Stack stack 1 2 3 4Stack load

funcs = []for i in range(4): def f(): print I

# funcs.append(f)

print funcs

i =0for f in funcs: i += 1 print id(f), f()[, , , ]

46255920 1None46309104 2None46309296 3None46363504 4None

Scoping . Local > global > Built-in Global/nonlocal

globalBuilt-in

Scope Namespacelocallocal

-Namespace dictionary / locals()

#

-Namespace : locals() locals() .__globals__ globals() context >>> def add(x,y) :... p="local variable"... print locals()... return x+ y... >>> >>> add(1,2){'y': 2, 'p': 'local variable', 'x': 1}3

>>> add.__globals__

(dict())

-return/yield .Return None Tuple .

return yield Generator (next())

Function Parameter

-Namespace : .

# def add(x, y) : return x+y

# add(1,2) # 3 returnAdd {x: None, y:None}Add {x: 1, y: 2}

mutable/immutable None

def f(a, l=[]) : l.append(a) return lf(1)f(2)f(3){ a:1, l :[1]} { a:2, l :[1,2]}{ a:2, l :[1,2,3]}f(1) f(2) f(3) List .def f(a, l=None) : l = [] l.append(a) return l

mutable() Return Mutable swap() Return #def swap(a,b) : x = a[:] a[:] = b[:] b[:] = x[:]

# a = [1]b = [2]print(swap(a,b))print(a,b) //[2] ,[1]

-/

# def add(x=10, y) : return x+y

# add(1,y=20) # 21 returnadd {x: 10, y:None}add {x: 1, y: 20}

--(*args)

# def add(*arg) : x =0 for y in arg : x=x+y return x

# add(1,2) # 3 returnadd {arg: None}add {arg: (1,2) }

--/(**args)

# def add(**arg) : return arg[x] + arg[y]

# add(x=1,y=2) # 3 returnadd {arg: None}add {arg: { x:1,y:2} }

Function Call

() (iteration, generation)

-

def factorial(n): print("factorial has been called with n = " + str(n)) if n == 1: return 1 else: result = n * factorial(n-1) print("intermediate result for ", n, " * factorial(" ,n-1, "): ",result) return result

print(factorial(5))

stack

iteration sequence >>> l= [1,2,3,4]>>> iter(l)

>>> li = iter(l)>>> li.next()1>>> li.next()2>>> li.next()3>>> li.next()4>>> li.next()Traceback (most recent call last): File "", line 1, in StopIteration>>>

:Generation exception >>> v = (i for i in l)>>> v

>>> v.next()0>>> v.next()1>>> v.next()2>>> v.next()3>>> v.next()4>>> v.next()Traceback (most recent call last): File "", line 1, in StopIteration>>> >>> def returnfunc(x) :... for i in x :... yield i... >>> p = returnfunc([1,2,3])>>> p

>>> p.next()1>>> p.next()2>>> p.next()3>>> p.next()Traceback (most recent call last): File "", line 1, in StopIteration>>> Generation ExpressionGeneration Function

: Generation Function(yield) Return Yield (next()) exception >>> def list_c(l) :... for i in l :... yield i... >>> list_c(l)

>>> v = list_c(l)>>> v.next()0>>> v.next()1>>> v.next()2>>> v.next()3>>> v.next()4>>> v.next()Traceback (most recent call last): File "", line 1, in StopIteration>>>

- : Curry

def f(a): print "function class object ",id(f) def g(b, c, d, e): print(a, b, c, d, e) return g

print " function instance ", id(f(1))f1 = f(1)f1(2,3,4,5)

def f1(a): def g1(b): def h1(c, d, e): print(a, b, c, d, e) return h1 return g1

f1(1)(2)(3,4,5)f1(1) g1(2) h1 (3,4,5) (1,2,3,4,5)

- : partial partial from functools import partialdef f2(a, b, c, d): print(a, b, c, d)

#

print partial(f2, 1, 2, 3)

g2 = partial(f2, 1, 2, 3)g2(4)Partial (1,2,3,4)

Nested Function

. # def outer() : # def inner() : pass

# # return inner()

def greet(name): # def get_message(): return "Hello # result = get_message()+name return result

# print greet("Dahl")

scope , mutable # def compose_greet_func(name): # # name def get_message(): return "Hello there "+name+"! # return get_message#greet = compose_greet_func(Dahl")print greet()

First Class Object

First Class Object(1)First Class .(variable) (parameter) (return value) 1 (first class object)

# func = addprint func

# def addplus(func,x,y) : return func(x,y) print addplus(add,5,5)

#

def addpass(func) : return func

print addpass(add)(5,5)

#

1010

First Class Object(2)1 (first class object)(runtime) (anonymous)

#

def addpass(func) : return func

print addpass(add)(5,5)

#lambda #

print addpass(lambda x,y: x+y)(5,5)

() def swap(a,b) :x = a[:]a[:] = b[:]b[:] = x[:]

func_var = swap # a = [1]b = [2]#print(swap(a,b))print(func_var(a,b))print(a,b) ( () )

# def greet(name): return "Hello " + name # def call_func(func): other_name = Dahl # return func(other_name)

# print call_func(greet)

# def compose_greet_func(): # def get_message(): return "Hello there! # return get_message

# : # greet = compose_greet_func()# : print greet()

- LambdaLambda return . .

Lambda :

()

Lambda Lambda 2 2 tuple

>>> x = lambda x,y : y,xTraceback (most recent call last): File "", line 1, in NameError: name 'x' is not defined>>>>>> x = lambda x,y : (y,x)>>> x(1,2)(2, 1)

Closure

Closure : context . variable scope .

Closure context ->

Closure : __closure__ def generate_power_func(n): out_v = 10.0 def nth_power(x): return x**n + out_v return nth_power

print clo.__closure__print clo.__closure__[0]print type(clo.__closure__[0])print clo.__closure__[0].cell_contentsprint type(clo.__closure__[1])print clo.__closure__[1].cell_contents(, )

4

10.0

__closure__

Closure : (1) .

def generate_power_func(n): print "id(n): %X" % id(n) print ' outer ', locals() def nth_power(x): print ' inner ', locals() #return x**n v = x**n # n = v + n #UnboundLocalError: local variable 'n' referenced #before assignment return v print "id(nth_power): %X" % id(nth_power) return nth_power

clo = generate_power_func(4)print clo(5)

immutable Locals() outer {'n': 4}inner {'x': 5, 'n': 4}

Closure : (2) Mutable Immutable binding (immutable) unboundlocalerror nonlocal mutable (, )

ContextContextLocalLocalIntFloatstringImmutable

context

Function Chaining

chian (parameter) def chain(obj) : return obj def cc(obj): print obj chain(cc)('str')1 2

#str

High Order Function

High Order Function(high order function) 2 , # def addList8(list): return reduce(add8, list)# def add8(*arg): v = [] for i in arg: v = v +i return v

# print addList8([[1, 2, 3],[4, 5],[6],[]])

print reduce(add8, [[1, 2, 3],[4, 5],[6],[]])# [1, 2, 3, 4, 5, 6][1, 2, 3, 4, 5, 6]

map map(f, iterable) (f) (iterable) f # 2 3# 5

list(map(lambda x: x ** 2, range(5)))

# : [0, 1, 4, 9, 16]

reduce reduce(f, iterable) (f) (iterable) f def addList7(list): return reduce(add, list) def add(*arg): x = 0 for i in arg : x = x + i return x print "addlist", addList7([1, 2, 3])

print "reduce ", reduce(add, [1, 2, 3])# addlist 6reduce 6

filter # 2 3#10 5 5 list(filter(lambda x: x < 5, range(10)))

# : [0, 1, 2, 3, 4]filter(f, iterable) (f) (iterable) f filter

Function Decorator

Decorator Chain : functools wraps

Decorator : functools functools wraps __doc__/__name__

Decorator Decorator wrapping Chain () 1

2 3()2(3) 31(2(3))@f1@f2

Decorator 1(2(3))()

Decorator Decorator .def func_return(func) : return func

def x_print() : print(" x print ")

x = func_return(x_print)x()def func_return(func) : return func

@func_returndef r_print() : print (" r print ")

r_print()

Decorator : wrapping Decorator wrapping Wrapping

def common_func(func) : def wrap_func() : return func() return wrap_func@common_funcdef r_func() : print " r func "

r_func()# r func

Decorator:()Decorator decorator def outer_f(func) :

def inner_f(*arg, **kargs) : result = func(*arg, **kargs) print(' result ', result) return result return inner_f

@outer_fdef add_1(x,y): return x+y

# x = add_1(5,5)print(' decorator ', x)# v = outer_f(add)v(5,5)

Functools Modulefunctools.wraps(wrapped[, assigned][, updated]) from functools import wrapsdef my_decorator(f): @wraps(f) def wrapper(*args, **kwds): print 'Calling decorated function' return f(*args, **kwds) return wrapper

@my_decoratordef example(): """Docstring""" print 'Called example function'

example()Functool import @wraps()Wrapper

Function decorator : ( ) wrapping

def tags(tag_name): def tags_decorator(func): def func_wrapper(name): return "{1}".format(tag_name, func(name)) return func_wrapper return tags_decorator

@tags("p")def get_text(name): return "Hello "+name

# print get_text("Dahl")

Functools Modulefunctools.wraps(wrapped[, assigned][, updated]) from functools import wrapsdef my_decorator(f): @wraps(f) def wrapper(*args, **kwds): print 'Calling decorated function' return f(*args, **kwds) return wrapper

@my_decoratordef example(): """Docstring""" print 'Called example function'

example()Functool import @wraps()Wrapper

Function decorator func decorate1(decorate2(decorat3(func))) #decorate1 def decorate1 : pass#decorate2 def decorate2 : pass#decorate3 def decorate3 : pass

@decorate1@decorate2@decorate3def func : pass

Functools Module: from functools import wrapsdef my_decorator0(x) : print x def my_decorator1(f): @wraps(f) def wrapper(*args, **kwds): print 'Calling decorated function' return f(*args, **kwds) return wrapper return my_decorator1

@my_decorator0('xxx')def example1(): """Docstring""" print 'Called example function' example1() Functool import @wraps()Wrapper

Function decorator f1(f2(add))(5,5) #decorator 1def f1(func) : def wrap_1(*args) : return func(*args) print " f1 call" return wrap_1

#decorator 2 def f2(func) : def wrap_2(*args) : return func(*args) print "f2 call" return wrap_2

#decorator @f1@f2def add(x,y) : print " add call " return x +y print add(5,5)

# print f1(f2(add))(5,5)#decorator f2 call f1 call add call 10# f2 call f1 call add call 10Decorator

Class

Class

Class Class

Class

Class Object

ClassObject 1Object 1Object 1 instanceclass [( )]: ... def 1(self[, 1, 2,,,]): ... def 2(self[, 1, 2,,,]): ... ...

Class 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

Class

Instance

Class .

Int Class >>> dir(int)['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']>>> Int Class __del__() . . context . int Class >>> v = int(1)>>> w = int(1)>>> z = int(1)>>> id(v)5939944>>> id(w)5939944>>> id(z)5939944>>> v = 2>>> id(v)5939932>>> id(1)5939944>>> v=1>>> id(v)5939944int Object instance

Class Object & instanceClass Object . (Namespace) . -

User definedClassInstanceInstanceInstanceBuilt-inClass

Object Scope Object Namespace

Class Member

Class MemberClass Object , , .

class Class_Member : cls_var = 0 @classmethod def cls_method(cls) : cls.cls_var = 1 print("call cls_method ", cls.cls_var)

@staticmethod def sta_method() : cls_var = 100 print("call sta_method ", cls_var)

def ins_method(self) : self.ins_var = 1 print('call ins method ', self.ins_var)

c = Class_Member()c.ins_method()print(c.__dict__)

# ('call cls_method ', 1)('call sta_method ', 100)#Class_Member {'sta_method': , '__module__': '__main__', 'ins_method': , 'cls_method': , 'cls_var': 1, '__doc__': None}

Predefined Class AttributesAttributeTypeRead/WriteDescription__dict__dictionaryR/WThe class name space.__name__stringR/OThe name of the class.__bases__tuple of classesR/OThe classes from which this class inherits.__doc__string OR NoneR/WThe classdocumentation string__module__stringR/WThe name of the module in which this class was defined.

Instance MemberInstance self

class Class_Member : cls_var = 0 @classmethod def cls_method(cls) : cls.cls_var = 1 print("call cls_method ", cls.cls_var) @staticmethod def sta_method() : cls_var = 100 print("call sta_method ", cls_var)

def ins_method(self) : self.ins_var = 1 print('call ins method ', self.ins_var)

c = Class_Member()c.ins_method()print(c.__dict__)

# ('call ins method ', 1){'ins_var': 1} #

Predefined Instance AttributesAttributeTypeRead/WriteDescription__dict__dictionaryR/WThe instance name space.__class__Base classRThe base class__doc__string OR NoneR/WThe instancedocumentation string

Class - cls cls

Instance -self Self

Method- self

Method- decorator . cls .

@classmethod : -Python 2.x classmethod() : Python 3.x

Method- decorator .

@staticmethod : Python 2.x staticmethod() Python 3.x

self, cls,

Accessing Members 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.salaryClass # : emp1 = Employee("Zara", 2000) # emp1.displayEmployee()

# : emp2 = Employee("Manni", 5000) # emp2.displayEmployee()

# print "Total Employee %d" % Employee.empCountInstance

Method Bound/unbound(1) binding self, cls >>> class Preson() :... def printP(self) :... print(' instance method ')... def printC(cls) :... print(' class method') >>> p = Preson() # >>> p.printP() # binding instance method >>> Preson.printP(p) # unbinding instance method >>>

binding

unbinding

Method Bound/unbound(2) self, cls TransformationCalled from an ObjectCalled from a ClassInstance methodf(*args)f(obj,*args)Static methodf(*args)f(*args)Class methodf(cls, *args)f(*args)

Method & Object Chain

Method Chainclass Person: def name(self, value): self.name = value return self def age(self, value): self.age = value return self def introduce(self): print "Hello, my name is", self.name, "and I am", self.age, "years old."

person = Person() # person.name("Peter").age(21).introduce()

Object Chain#class class A: def __init__(self ): print 'a' self.b = B()

#object chain class class B: def __init__(self ): print 'b' def bbb(self): print "B instance method " a = A()

print a.b.bbb() (Association, Composite )

.. #abB instance method None

-Creating Instance __init__() () class Employee: 'Common base class for all employees' empCount = 0

def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1

"This would create first object of Employee class"emp1 = Employee("Zara", 2000)"This would create second object of Employee class"emp2 = Employee("Manni", 5000)

- Destroying Objects #!/usr/bin/python

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 = pt1pt3 = pt1print id(pt1), id(pt2), id(pt3) # prints the ids of the obejctsdel pt1del pt2del pt3

Class

(1)

>>> one = 1>>> type(one)

>>> type(type(one))

>>> type(one).__bases__(,)>>> >>> object

>>> type >>> type(object)

>>> object.__class__

>>> object.__bases__ ()>>> type.__class__

>>> type.__bases__ (,)>>> isinstance(object, object) True>>> isinstance(type, object) True>>> isinstance(object, type)True

objecttypeintfloatstr

(2)>>> list

>>> list.__class__

>>> list.__bases__ (,)>>> tuple.__class__, tuple.__bases__ (, (,))>>> dict.__class__, dict.__bases__ (, (,))>>>>>> mylist = [1,2,3] >>> mylist.__class__

base object

typeobjectlistmylist

issubclass/isinstance >>> issubclass(list,object)True>>> list.__bases__(,)>>> issubclass(list, type)False>>> issubclass() : __bases__ isinstance() : __ class__ >>> isinstance(list, type)True>>> list.__class__

>>> >>> isinstance(list, object)True>>> issubclass isinstance

Class & instance namespaceClass Object , , . > > Built-in Class . .

>>> class Simple : ... pass... >>> Simple

>>> Simple.__name__'Simple>>> Simple.__dict__{'__module__': '__main__', '__doc__': None}>>> s = Simple()>>> s.__dict__{}>>> s.name = "Simple instance">>> s.__dict__{'name': 'Simple instance'}Instance Class

Members() AccessClass/Instance >>> # class >>> class C(object): ... classattr = "attr on class... >>> # >>> cobj = C() >>> cobj.instattr = "attr on instance" >>> >>> cobj.instattr 'attr on instance' >>> cobj.classattr 'attr on class (.) Cclassattr

cobj:Cinstattr

cobj = C()

Members() Access -Class/Instance __dict__ () >>> # __dict__ >>> # Class >>> C.__dict__['classattr'] 'attr on class' >>> # Instance >>> cobj.__dict__['instattr'] 'attr on instance' >>>>>> C.__dict__ {'classattr': 'attr on class', '__module__': '__main__', '__doc__': None}>>>>>>>>> cobj.__dict__ {'instattr': 'attr on instance'} >>>C

cobj:C

cobj = C()__dict__:dictclassattr

__dict__:dictclassattr

Members() AccessClass Class >>> #Class >>> class C(object): ... classattr = "attr on class... def f(self):... return "function f" ... >>> # >>> cobj = C() >>> # >>> cobj.classattr is C.__dict__['classattr'] True Cclassattrfcobj:Cinstattr

cobj = C()

Members() Access- >>> # >>> # is >>> cobj.f is C.__dict__['f'] False >>>>>> C.__dict__ {'classattr': 'attr on class', '__module__': '__main__', '__doc__': None, 'f': } >>> >>> cobj.f >>> # >>> # >>> C.__dict__['f'].__get__(cobj, C) C

cobj:C

cobj = C()__dict__:dictclassattrf__dict__:dictclassattrf

Controlling Attribute AccessInstance Attribute

__getattr__(self, name)__setattr__(self, name, value)__delattr__(self, name)__getattribute__(self, name)

Controlling Attribute Access class A() : __slots__ =['person_id', 'name'] def __init__(self, person_id, name) : self.person_id = person_id self.name = name def __getattr__(self, name) : return self.__dict__[name] def __setattr__(self, name, value): if name in A.__slots__ : self.__dict__[name] = value else: raise Exception(" no match attribute") def __delattr__(self, name) : del self.__dict__[name]

def __getattribute__(self, name): return self.__dict__[name]a = A(1,'dahl')

print a.__getattr__('name')print a.__getattr__('person_id')

print a.__dict__

print a.__setattr__('name','moon')print a.__setattr__('person_id',2)

print a.__getattr__('name')print a.__getattr__('person_id')

print a.__delattr__('name')print a.__dict__

a.name = 'gahl'

#a.s = 1

print a.__dict__

Class Inheritance

Inheritance class : pass class ( ) : pass

class ( , ) : pass

Inheritance- scope

class ( , ) : pass

Inheritance - 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 childc.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

#

Calling child constructor Calling child method Calling parent method Parent attribute : 200Class

Mixin

class Mixin : def add(self,x,y) : return self.x + self.y def sub(self,x,y) : if isinstance(self, String) : return " String no support" else : return self.x - self.y

class Number(Mixin) : def __init__(self, x,y) : self.x = x self.y = y

class String(Mixin) : def __init__(self, x,y) : self.x = x self.y = y n1 = Number(5,6)n1.add(n1.x,n1.y)n1.sub(n1.x,n1.y)

s1 = String("hello ", "world")print s1.add(s1.x, s1.y)print s1.sub(s1.x, s1.y)

Overriding

Overriding Overriding class : def method(self) : pass class ( ) : def method(self) : pass

OverridingBuiltin

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)

# __init__ overridingv1 = Vector(2,10) v2 = Vector(5,-2)

# __add__ overriding print v1 + v2

Information Hiding

Information hiding -__ : Private ( ) mangling .____ : protected ( )

Information hiding - : public ( ) __ : Private ( ) mangling .___ _ : protected ( ) dont touch this, unless youre a subclass >>>class foo: def __secret(self): pass

foo.__secret => AttributeError: __secret >>>foo.__dict__{'_foo__secret': , '__module__': '__main__', '__doc__': None} Private Class Namespace

Information hiding - ____ :

Information hiding Descriptor(Property) Property .Descriptor , Property @property decorator property Class PInstance p1{x: }Descriptor/Property x

p1.x Property

desciptor

Descriptor Protocol

Descriptor " " __get__(self, instance, owner),__set__(self,instance, value),__delete__(self, instance).

Descriptor Method descriptor Data descripter Method descriptor __get__(self, instance, owner) Data descriptor __get__(self, instance, owner) __set__(self,instance, value), __delete__(self, instance)

Descriptor : int.__add__Method descriptor __get__(self, instance, owner)

P =1# p.__add__(3) # 4# type(p).__add__.__get__(p,int)(3) # 4#class int.__add__.__get__(1,int)(3)

Descriptor : binding behavior binding

Direct CallInstance BindingClass BindingSuper Bindingclass D(object) : def __init__(self, x) : self.x = x def __get__(self,instance=None,cls=None) : return self.x class D1(D) : def __init__(self, x) : D.__init__(self,x)

d = D(1)print " d"print d.__dict__print d.xprint " direct call",d.__get__()print " Class binding call ",D.__get__(d,d)print "instance binding",type(d).__get__(d,d)d1 = D1(2)print " d1"print d1.__dict__print d1.xprint " direct call",d1.__get__()print " Class binding call ", D1.__get__(d1,d1)print "instance binding",type(d1).__get__(d1,d1)print D1.mro()print "super binding",super(D1,d1).__get__(d1,d1)

Creating descriptorDescriptor

class Descriptor(object): def __init__(self): self._name = '' def __get__(self, instance, owner): print "Getting: %s" % self._name return self._name def __set__(self, instance, name): print "Setting: %s" % name self._name = name.title() def __delete__(self, instance): print "Deleting: %s" %self._name del self._name

class Person(object): name = Descriptor()>>> user = Person() >>> user.name = 'john smith' Setting: john smith >>> user.name Getting: John Smith 'John Smith>>> del user.name Deleting: John Smith

Creating Property- (1) Property Wrapping

property(fget=None, fset=None, fdel=None, doc=None)

class P:

def __init__(self,x): self.x = x def getx(self) : return self.x def setx(self, x) : self.x = x def delx(self) : del self.x

x = property(getx,setx,delx," property test ")

Getter, setter, deleter Property ( _x )

Creating Property (2) Property p1 = P(1001)print id(p1.x)print P.__dict__['x']print id(p1.__dict__['x'])print p1.xp1.x = -12print p1.xprint p1.__dict__#44625868

446258681001-12{'x': -12}

Creating Property decorator(1) Property Wrapping

property(fget=None, fset=None, fdel=None, doc=None)

class P:

def __init__(self,x): self.x = x @property def x(self): return self.__x @x.setter def x(self, x): self.__x = x @x.deleter def x(self): del self.x Getter, setter, deleter Property ( _x )

Creating Property decorator(2)Property p1 = P(1001)print id(p1.x)print P.__dict__['x']print id(p1.__dict__['x'])print p1.xp1.x = -12print p1.xprint p1.__dict__#44625916

446259161001-12{'x': -12}

Object

Object

?

.

?

>>> type

>>> int

>>> float

>>> str

>>> list

>>> tuple

>>> dict

>>> file

>>> re

>>> re.__class__

Object Scope ( instance )

: > > >builtin Class

.

Predefined Instance AttributesAttributeTypeRead/WriteDescription__dict__dictionaryR/WThe instance name space__class__classR/WThe class of this instance

Literal

?

Immutuable()Mutuable()

. .

Value Immutuable() : -

Mutuable() : () - ,

a = 10 # 10 Print(id(a)) # 10 # 1234567def aa(a) : aa = locals() print(aa[a]) # 10 print(id(aa[a])) # 1234567

aa(a) # a aa # call by Value . .

Object Value Bound/unbound Binding Binding .Unbinding List comprehension - range(), eval(), exec() - ( *args, ** args) - , binding -

Exception

Exception

try: Exception ...................... except ExceptionI: Exception except ExceptionII: Exception ...................... else: Exception

User Exception User Exception Exception # Exception class Uexcept(Exception) : def __init__(self,ex_code,ex_err) : self.ex_code = ex_code self.ex_err = ex_err # Exception def R_call() :

try: i = i + 1 except Exception as err : x = Uexcept("1111",err) print "ex coed ",x.ex_code print "ex_err ", x.ex_err raise x #try : R_call()except Uexcept as err : print err.ex_code print err.ex_err # ex coed 1111ex_err local variable 'i' referenced before assignment1111local variable 'i' referenced before assignment

Try-except-[else] else

try: f = open('foo.txt', 'r')except FileNotFoundError as e: print(str(e))else: data = f.read() f.close()

else

Try-[except]-finally except finally try : R_call()except Uexcept as err : print err.ex_code print err.ex_errfinally : print "pass"finally

Exception Except as , # def temp_convert(var): try: return int(var) #except ValueError , Argument : except ValueError as Argument: print Argument.message print "The argument does not contain numbers\n", Argument

# temp_convert("xyz");# invalid literal for int() with base 10: 'xyz'The argument does not contain numbersinvalid literal for int() with base 10: 'xyz

Raising exception exception raise exception # def get_age(): age = int(input("Please enter your age: ")) if age < 0: # Create a new instance of an exception my_error = ValueError("{0} is not a valid age".format(age)) # exception raise my_error return age

>>> get_age() Please enter your age: 42 42 >>> get_age() Please enter your age: -2 Traceback (most recent call last): File "", line 1, in File "learn_exceptions.py", line 4, in get_age raise ValueError("{0} is not a valid age".format(age))ValueError: -2 is not a valid age

Exception class Exception args massage >>> a = Exception(' messsage ')>>> a.args(' messsage ',)>>> a.message' messsage '>>>

Exception(1) EXCEPTION NAMEDESCRIPTIONExceptionBase class for all exceptionsStopIterationRaised when the next() method of an iterator does not point to any object.SystemExitRaised by the sys.exit() function.StandardErrorBase class for all built-in exceptions except StopIteration and SystemExit.ArithmeticErrorBase class for all errors that occur for numeric calculation.OverflowErrorRaised when a calculation exceeds maximum limit for a numeric type.FloatingPointErrorRaised when a floating point calculation fails.ZeroDivisonErrorRaised when division or modulo by zero takes place for all numeric types.AssertionErrorRaised in case of failure of the Assert statement.AttributeErrorRaised in case of failure of attribute reference or assignment.EOFErrorRaised when there is no input from either the raw_input() or input() function and the end of file is reached.ImportErrorRaised when an import statement fails.KeyboardInterruptRaised when the user interrupts program execution, usually by pressing Ctrl+c.LookupErrorBase class for all lookup errors.IndexErrorKeyErrorRaised when an index is not found in a sequence.Raised when the specified key is not found in the dictionary.

Exception(2) EXCEPTION NAMEDESCRIPTIONNameErrorRaised when an identifier is not found in the local or global namespace.UnboundLocalErrorEnvironmentErrorRaised when trying to access a local variable in a function or method but no value has been assigned to it.Base class for all exceptions that occur outside the Python environment.IOErrorRaised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.Raised for operating system-related errors.SyntaxErrorIndentationErrorRaised when there is an error in Python syntax.Raised when indentation is not specified properly.SystemErrorRaised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.SystemExitRaised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.ValueErrorRaised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.RuntimeErrorRaised when a generated error does not fall into any category.NotImplementedErrorRaised when an abstract method that needs to be implemented in an inherited class is not actually implemented.

Traceback Exception Traceback Traceback print .import traceback

try: 1/0except Exception: print 'the relevant part is: '+ traceback.format_exc()

# Exception Traceback print "exception print : " + e.message

#the relevant part is: Traceback (most recent call last): File "C:/myPython/myproject/traceback_test.py", line 35, in 1/0ZeroDivisionError: integer division or modulo by zero

exception print : integer division or modulo by zero

Python File

File Object Object File . iterable ContainerLine Line Line Line Line Line

File Object Method(1)Methodfile.close()Close the filefile.flush() file.fileno()Return the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating systemfile.isatty()ReturnTrueif the file is connected to a tty(-like) device, elseFalse.file.next()A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for example, for line in f: print line.strip()), the next() method is called repeatedly. file.read([size])Read at mostsizebytes from the file (less if the read hits EOF before obtainingsizebytes).file.readline([size])Read one entire line from the file.file.readlines([sizehint]) ..

File Object Method(2)Methodfile.xreadlines() , .file.seek(offset[,whence]) .(whence offset , 1 offset, 2 offset ) - seek(n) : n - seek(n, 1) : n (n , ) - seek(n, 2) : n (n )file.tell() .file.truncate([size]) . ..file.write(str)Write a string to the file. There is no return value.file.writelines(sequence) .

File Object VariableMethodfile.closedbool indicating the current state of the file object.file.encodingThe encoding that this file uses.file.errorsThe Unicode error handler used along with the encoding.file.modeThe I/O mode for the file. If the file was created using the open() built-in function, this will be the value of the mode parameter.file.nameIf the file object was created using open(), the name of the file. Otherwise, some string that indicates the source of the file object, of the form . file.newlinesIf Python was built with universal newlines enabled (the default) this read-only attribute exists, and for files opened in universal newline read mode it keeps track of the types of newlines encountered while reading the file. file.softspaceoolean that indicates whether a space character needs to be printed before another value when using the print statement.

File : = open(, ) : .close()f = open("newfile.txt", 'w') f.close() newfile.txt

File r - r+ - a - ()a+ ( )w - w+ ( )t b- rb rb+ wb+ ( )ab+ ( )

File with With f = open(withfile.txt", 'w') f.write(Hello World !!!!") f.close()With file.close() with file close with open(" withfile.txt", "w") as f: f.write(" Hello World !!!!")

File .write() f = open("newfile.txt", 'w')

#for 10 for i in range(1, 11): # line = "%d .\n" % i f.write(line)

f.close() newfile.txt 10

newfile.txt 1 .2 .3 .4 .5 .6 .7 .8 .9 .10 .

File w = open(, a) .write() f = open("newfile.txt", 'w')

for i in range(1, 11): # line = "%d .\n" % i f.write(line)

f.close()

# f = open("newfile.txt",'a')

for i in range(11, 21): data = "%d .\n" % i f.write(data)

f.close() newfile.txt 10 20

newfile.txt 1 .2 .3 .4 .5 .6 .7 .8 .9 .10 .11 .12 .13 .14 .15 .16 .17 .18 .19 .20 .

File - .readline() # f = open("newfile.txt", 'r') # line = f.readline() print(line)

f.close() newfile.txt

1 .

File - .readline(), .readlines(), .read() f = open("newfile.txt", 'r')

while True: line = f.readline() if not line: break print(line)

f.close()f = open("newfile.txt", 'r') data = f.read()

print(data)

f.close() iterable f = open("newfile.txt", 'r') data = f.read()

print(data)

f.close()

eval : Expression Eval >>> eval("1+2")3>>>

exec : Statement Exec >>> exec('print "hello world"')hello world>>>

Text Class (1) class Sandbox(object): def execute(self, code_string): exec code_string s = Sandbox()code = """print "Hello world""""s.execute(code)

#Hello world

Text Class (2)file, open, eval, exec keyword .class Sandbox(object): def execute(self, code_string): exec code_string code1 = """file("test.txt", "w").write("Kaboom!\\n")"""

s.execute(code1)

# test.txt Kaboom!

Text Class (3)file, open, eval, exec keyword __builtins__ .class Sandbox(object): def execute(self, code_string): keyword_blacklist = ["file", "open", "eval", "exec"] for keyword in keyword_blacklist: if keyword in code_string: raise ValueError("Blacklisted") exec code_string s = Sandbox()code = """print "Hello world""""s.execute(code)

code1 = """file("test.txt", "w").write("Kaboom!\\n")"""s.execute(code1)

#Hello world

# ValueError: Blacklisted

Command

Command line $ python h # command help usage: python [-BdEiOQsRStuUvVWxX3?] [-c command | -m module-name | script | - ] [args]OptionDescription-dprovide debug output-Ogenerate optimized bytecode (resulting in .pyo files)-Sdo not run import site to look for Python paths on startup-vverbose output (detailed trace on import statements)-Xdisable class-based built-in exceptions (just use strings); obsolete starting with version 1.6-c cmdrun Python script sent in as cmd stringfilerun Python script from given file

Command line - $ python test.py arg1 arg2 arg3 #!/usr/bin/python import sys print 'Number of arguments:', len(sys.argv), 'arguments.' print 'Argument List:', str(sys.argv) test.py test.py

Sys argv

sys.argv[1]

#Number of arguments: 4 arguments.Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

Python

PIP command

Command Pip [options] []

PIP : C:\Python27\Lib\site-packages

PIP : flask

Python re

: :

ExampleDescriptionpythonMatch "python".

(character class, []) [] "[] " [a-zA-Z] : [0-9] : ^ (not) : [^0-9] ExampleDescription[Pp]ythonMatch "Python" or "python"rub[ye]Match "ruby" or "rube"[aeiou]Match any one lowercase vowel[0-9]Match any digit; same as [0123456789][a-z]Match any lowercase ASCII letter[A-Z]Match any uppercase ASCII letter[a-zA-Z0-9]Match any of the above[^aeiou]Match anything other than a lowercase vowel[^0-9]Match anything other than a digit

\d- ,[0-9] \D- ,[^0-9] \s- whitespace ,[ \t\n\r\f\v] . (space) \S- whitespace ,[^ \t\n\r\f\v] \w- +(alphanumeric) ,[a-zA-Z0-9] \W- alphanumeric ,[^a-zA-Z0-9]

-PatternDescription\wMatches word characters.\WMatches nonword characters.\sMatches whitespace. Equivalent to [\t\n\r\f].\SMatches nonwhitespace.\dMatches digits. Equivalent to [0-9].\DMatches nondigits.\AMatches beginning of string.\ZMatches end of string. If a newline exists, it matches just before newline.\zMatches end of string.\GMatches point where last match finished.\bMatches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.\BMatches nonword boundaries.\n, \t, etc.Matches newlines, carriage returns, tabs, etc.\1...\9Matches nth grouped subexpression.\10Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code.

^ / $^ re.MULTILINE ^ [^] \^ $ $ [$] \$

Anchor ExampleDescription^PythonMatch "Python" at the start of a string or internal linePython$Match "Python" at the end of a string or line\APythonMatch "Python" at the start of a stringPython\ZMatch "Python" at the end of a string\bPython\bMatch "Python" at a word boundary\brub\B\B is nonword boundary: match "rub" in "rube" and "ruby" but not alonePython(?=!)Match "Python", if followed by an exclamation point.Python(?!!)Match "Python", if not followed by an exclamation point.

DOT(.)dot(.) \n re.DOTALL \n a.b : "a + + ba[.]b : "a + Dot(.) + b"

(*)* a 0 Match ca*tctYes"a" 0 ca*tcatYes"a" 0 (1 )ca*tcaaatYes"a" 0 (3 )

(+)+ 1 Match ca+tctNo"a" 0 ca+tcatYes"a" 1 (1 )ca+tcaaatYes"a" 1 (3 )

(?)? {0, 1}Match ab?cabcYes"b" 1 ab?cacYes"b" 0

({m,n}){} .{m, n} m n {1,}+ {0,}* Match ca{2}tcatNo"a" 1 ca{2}tcaatYes"a" 2 ca{2,5}tcatNo"a" 1 ca{2,5}tcaatYes"a" 2 ca{2,5}tcaaaaatYes"a" 5

(\) \section : \s whitespace [ \t\n\r\f\v]ection \\section : \\\ \\ \\\\ 4 r\section : Raw String

Alternatives (|,or)| "or" A|B A B

ExampleDescriptionpython|perlMatch "python" or "perl"rub(y|le))Match "ruby" or "ruble"Python(!+|\?)"Python" followed by one or more ! or one ?

Grouping ( )( )

ExampleDescription(re)Groups regular expressions and remembers matched text.(?imx)Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected.(?-imx)Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected.(?: re)Groups regular expressions without remembering matched text.(?imx: re)Temporarily toggles on i, m, or x options within parentheses.(?-imx: re)Temporarily toggles off i, m, or x options within parentheses.(?#...)Comment.(?= re)Specifies position using a pattern. Doesn't have a range.(?! re)Specifies position using pattern negation. Doesn't have a range.(?> re)Matches independent pattern without backtracking.

Grouping ( ) -line = "Cats are smarter than dogsmatchObj = re.match( r'(.*) are (.*?) (.*)', line, re.M|re.I)Cats (.*) , smarter (.*?) , than dogs (.*) re.I - , Re.m

ExampleDescription\D\d+\DNo group: + repeats \d(\D\d)+Grouped: + repeats \D\d pair([Pp]ython(, )?)+Match "Python", "Python, python, python", etc.

ExampleDescription([Pp])ython&\1ailsMatch python&pails or Python&Pails(['"])[^\1]*\1Single or double-quoted string. \1 matches whatever the 1st group matched. \2 matches whatever the 2nd group matched, etc.

.

re p = re.compile('ab*', re.IGNORECASE) : re.IGNORECASE >>> import re>>> mat = re.compile("[a-z]+")>>> mat

>>>

>>> m = re.match('[a-z]+', "python")>>> m.group()'python'>>> mo2 = re.match("[a-z]+","abc")>>> mo2.group()'abc'>>> Comile() re (match() )

: match, search match object None match(,,) .search(,,) .

line = "Cats are smarter than dogs"matchObj = re.match( r'(.*) are (.*?) (.*)', line, re.M|re.I)

if matchObj:print "matchObj.group() : ", matchObj.group()print "matchObj.group(1) : ", matchObj.group(1)print "matchObj.group(2) : ", matchObj.group(2)print "matchObj.group(3) : ", matchObj.group(3)else:print "No match!!"(.*) (.*?) 0 1Group()

: match, search match object None sub(pattern,replace,string) .

phone = "010-959-559 # This is Phone Number"# num = re.sub(r'#.*$', "", phone)print "Phone Num : ", num# num = re.sub(r'\D', "", phone) print "Phone Num : ", num #.*$ # $( ) \D [^0-9]

:Greedy vs Non-Greedy match, search match object None sub(pattern,replace,string) .

s = 'Title'print len(s)

print(re.match('', s).span())print(re.match('', s).group())

print(re.match('', s).span())print(re.match('', s).group()) Title'

-Compile

Compile optionsDOTALL, S -. IGNORECASE, I - MULTILINE, M (^,$ )VERBOSE, X - verbose ( )>>> re.compile('.*')

>>>

Compile Options- DOTALL, S . (\n) . \n re.DOTALLre.S .>>> SS = re.compile('.ake')>>> RR = SS.match('\nake')>>> RR>>> RR == NoneTrue\n. . re.S .>>> SS = re.compile('.ake',re.S)>>> RR = SS.match('\nake')>>> RR == NoneFalse>>> RR.group()'\nake'>>>

Compile Options-IGNORECASE, I re.IGNORECASEre.I .>>> II = re.compile('[a-z]+')>>> ii = II.match('Python')>>> ii == NoneTrue>>> [a-z] re.I .>>> II = re.compile('[a-z]+',re.I)>>> ii = II.match('Python')>>> ii == NoneFalse>>> ii.group()'Python'>>>

Compile Options-MULTILINE, M re.MULTILINE re.M ^, $ . ^ $ ^ - , $ - ^python "python" , python$ "python" >>> MM = re.compile('^Hello\s\w+')>>> data = """Hello World... Hello Dahl... Hello Moon""">>> mm = MM.match(data)>>> mm.group()'Hello World'>>>re.MULTILINE ^ .>>> MM = re.compile('^Hello\s\w+',re.M)>>> MM.findall(data)['Hello World', 'Hello Dahl', 'Hello Moon']

Compile Options-VERBOSE, X >>> charref = re.compile(r'&[#](0[0-7]+|[0-9]+|x[0-9a-fA-F]+);') .

.

re.VERBOSE whitespace . ([] whitespace )

# .>>> charref = re.compile(r""" &[#] # Start of a numeric entity reference ( 0[0-7]+ # Octal form | [0-9]+ # Decimal form | x[0-9a-fA-F]+ # Hexadecimal form ) ; # Trailing semicolon """, re.VERBOSE)

Compile match, search match object None match - search Methodmatch() .search() .findall() (substring) finditer() (substring) iterator

ParameterDescriptionpatternstring flags options or(|)

match match objectMatch Object Match() Methodgroup() .start() .end() .span() (, )

>>> mat = re.compile("[a-z]+")>>> mat

>>> >>> mo = mat.match('abc')>>> mo

>>> >>> mo.group()'abc'>>> >>> mo.start()0>>> mo.end()3>>> mo.span()(0, 3)>>> # >>> if mat.match(" abc") == None :... print("mismatch")... mismatch

search match object Methodgroup() .start() .end() .span() (, )

>>> mat = re.compile("[a-z]+")>>> mat

>>> >>> so1 = mat.search("123abc")>>> so1

>>> so1.group()'abc'>>> so1.start()3>>> so1.end()6>>> so1.span()(3, 6)>>>

search match object Methodgroup() .start() .end() .span() (, )

>>> mat = re.compile("[a-z]+")>>> mat

>>> >>> so1 = mat.search("123abc")>>> so1

>>> so1.group()'abc'>>> so1.start()3>>> so1.end()6>>> so1.span()(3, 6)>>>

(1/2)1. >>> import re>>> p = re.compile("[a-zA-Z0-9]+")>>> p

>>> p.__class__

>>> p.__class__.__name__'SRE_Pattern'>>>2. Match object >>> m = p.match("python")>>> m

>>> m.__class__.__name__'SRE_Match'>>>

(2/2)3. >>> m.group()'python'>>> m.span()(0, 6)>>>

Pickle

Pickle pickle import pickle

# shoplistfile = 'shoplist.data

# shoplist = ['apple', 'mango', 'carrot']# f = open(shoplistfile, 'wb')

# pickle.dump(shoplist, f)f.close()

# del shoplist

# f = open(shoplistfile, 'rb')

# storedlist = pickle.load(f)

print storedlist

Python OS

OS : OS OS >>> import os>>> # OS >>> os.name'nt'>>>

OS : directory OS >>> import os>>> # >>> os.getcwd()'C:\\myPython\\myproject>>> # >>> os.path.abspath('.')'C:\\myPython\\myproject>>> # >>> os.path.abspath('..')'C:\\myPython'>>> # >>> os.listdir('.')['.spyderproject', '.spyderworkspace', 'aaa.txt', 'abc.txt]

OS : directory OS >>> os.getcwd()'C:\\myPython\\myproject'>>> os.chdir('../kakao')>>> os.getcwd()'C:\\myPython\\kakao'>>>

Python sys

SYS : Python >>> import sys>>> sys.version'2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]>>> sys.version_infosys.version_info(major=2, minor=7, micro=5, releaselevel='final', serial=0)

SYS : Command-line argumentsSys arguments command window .import sys

# command line arg print sys.argv

# command line arg

for i in range(len(sys.argv)): if i == 0: print "Function name: %s" % sys.argv[0] else: print "%d. argument: %s" % (i,sys.argv[i])C:\myPython\myproject>python sys_com.py arg1 arg2['sys_com.py', 'arg1', 'arg2']Function name: sys_com.py1. argument: arg12. argument: arg2

C:\myPython\myproject>python sys_com.py ['sys_com.py']Function name: sys_com.pySys_com.py Command window

SYS : ide arg Dispalyhook callable arg >>> import sys>>> #arg >>> v = (10,10)>>> # >>> def add(v) :... print v[0]+ v[1]... >>> # >>> sys.displayhook = add>>> #arg >>> v20>>>

help() Sys.displayhook

SYS : Command -input (1)Command . string # add_test.py

import syswhile True: # 3.0 # s = input(Enter something :) s = raw_input('Enter something : ') if s == 'quit': break print 'Length of the string is', len(s) print 'string ', s print 'Done#command line C:\myPython\myproject> python add_test.py10Quit#Enter something : Length of the string is 2string 10Enter something : Done

SYS : Command -input (2)Text File Command . string # add_test.py

import syswhile True: # 3.0 # s = input(Enter something :) s = raw_input('Enter something : ') if s == 'quit': break print 'Length of the string is', len(s) print 'string ', s print 'Done#add_test.txt. 10Quit

#command line C:\myPython\myproject> python add_test.py < add_test.txt

#Enter something : Length of the string is 2string 10Enter something : Done

SYS : ide-input ide . string # add_test.py

import syswhile True: # 3.0 # s = input(Enter something :) s = raw_input('Enter something : ') if s == 'quit': break print 'Length of the string is', len(s) print 'string ', s print 'Done#ide #ide 10 Enter something : 10Length of the string is 2string 10#ide quit Enter something : quitDone