Академический Документы
Профессиональный Документы
Культура Документы
S = '\\' OR '\a'
S.capitalize()
S.casefold()
S.center(width [, f ill])
S.isalnum()
S.isalpha()
S.isdecimal()
S.isdigit()
S.isidentif ier()
S.islower()
S.isnumeric()
S.isprintable()
S.isspace()
S.istitle()
S.isupper()
S.join(iterable)
S.ljust(width, 'f ill')
S.lower()
S.lstrip([chars])
S.partition(sep)
S.rjust(width [, f ill])
S.rpartition(sep)
S.rstrip([chars])
S.strip([chars])
S.swapcase()
S.title()
S.translate(in,out)
S.upper()
S.zf ill(width)
S.list()
Lists-Mutable
**Assign values to position**
L[i][j]
Access list value
L.len()
Returns length
A= L[:]
A copies all values of L
L.append(x)
Adds element to end
L.extend([x,y,z])
Concatenates the lists
L.insert(i,x)
Insert at value or range
L.index(x)
Return index position
L.count(x)
range(x,y,z)
x to y linspace w/ z space
L.sort(func)
Sorts by alpha (or, func)
L.pop()
Delete and return last item
L.reverse()
Reverses list- changes L
D=list(zip(['x','y'],[1,2])) Zips/fuses vars to values
L.copy()
Create copy. Not a reference
**Be sure to consider Shared References issues**
Object Classif ication:
Object Type Category
Mutable
Numbers (all) Numeric
No
Strings (all)
Sequence
No
Lists
Sequence
Yes
Dictionaries
Mapping
Yes
Tuples
Sequence
No
Files
Extension
N/A
Sets
Set
Yes
frozenset
Set
No
bytearray
Sequence
Yes
Loops
For, while, while... else,
While x: Loops till no no more X
while true: Loops till hits break
Break:
Closes current loop
Continue: Jumps to top of loop
Pass:
Empty placeholder
Iterations
x=iter(L) Create an iterable
x.__next__()
Try: check= iter(x) Iterable check
L=[x for x in ['x','','y'] if bool(x)]
Dictionaries-Mutable
**Assign values to keys**
D={'title':'x',name'':'y'}
C = D.copy()
Copy values from D to C
D.keys()
Creates list of keys
D.items()
List of key + value(s) pairs
sorted(D1.items())
Sorted list of key value pair
D.values()
Creates list of values
D.clear()
Clears all values from list
D.update(D2)
Adds key value pair (D2) to D
D.get(key, default?)
Returns value assoc. with key
D.pop(key, default?)
Removes value assoc w. key
D.popitem()
Removes arbitrary (key, value)
D=dict(zip(['x','y'],[1,2])) Creates dict with 2 lists
D.keys() & D.keys()
D1 > OR < OR == D2 Compare dict magnitude
D[2]= 'test'
Can use int keys
D.copy.deepcopy()
Copies values, not references
**D
Unpacks dictionary
D={x:x**2 for x in range(5)} Create dict with loop
D.setdefault(key,default?) Look with key, if no use default
D={'cto':{'title':'x',name'':'y'}} Create nested dict
range()
raw_input()
reduce()
reload()
repr()
reversed()
round()
set()
setattr()
slice()
sorted()
staticmethod()
str()
sum()
super()
tuple()
type()
unichr()
unicode()
vars()
xrange()
zip()
__import__()
apply()
buffer()
coerce()
Intern()
print()
property()
Python Statements
=
Assignment
Pass
Empty placeholder (if, else)
Break
Loop exit
Continue
Continue Loop
Def
Create function and method
Return
function results
Yield
Generator. Value not stored.
Global
Create global function
Nonlocal
Only in 3.x
Class
Create a class
Try/except/f inally
Catching exceptions
Raise
Trigger exception
Assert
Debugging checks
With/As
Similar to try... f inally
Del
Delete references
**Many more, but obvious (eg. For)
If Statements
If, elif, else
Same functionality
A= [z,y][bool(x)] Another way of writing if else
If not
Inverts if logic
Functions
Modules Continued
*Functions are executed at runtime and created using def
*If variable @ top level of module starts with _
not imported with
Each function call creates a new local scope
from statement
*Factory Functions OR Closures are used to generate event
*__main__ indicates a f iles being executed form top level script
handlers on the f ly.
Object Orientated Programming
*Using arguments like *args OR **kargs (lists and dict respectively) *Inheritance in python built around object.attribute
has advantage of not needing to know # of args beforehand
*Attribute fetches can be thought of as tree fetches
*Argument may be passed by order or assignment
Classes: Attributes provide behavior. Top level attr. assign
*Use global vars only when needed
Instances: concrete items in program domain. Attr assign __self__
*Each function should have a single unif ied purpose
__init__ : used as constructor in python. If used with self.var1
*Function is an object. Can be assigned to var
the variable is available for lifetime of object
*dir(module) lists function names
*OOP: override generic class behavior by creating a method with
Lambda Functions
the same name but lower in class tree
**lambda function is not bound to a name, ex:
Ex. : Class subclass(superclass)
g= lambda x: x**2
*Created branched lambda functions
*When augmenting methods/ Customizing behavior:
*Useful when you need code to be close to where you are working Class Manager(Person):
{1: (lambda: 2+2), 2: (lambda: 2*4), 3: (lambda: 2**6)}[key]()
Def giveCheck(self, percent, bonus):
*Insert if else control f low
Person.giveCheck(self, paycheck+bonus)
lower = (lambda x, y: x if x < y else y)
**Good factoring: inherit original method form class
*Action = (lambda x: (lambda y: x + y)) **initialize action w. #
*list(map((lambda x: x+3),values))
*Customizing constructors def __init__(self, name, job=none):
*list(f ilter((lambda x: x>3),values)) **Filters values per condition
Class Manager(Person):
Map
Def __init__(self, name):
*Map is very powerful. It takes a set of values as an input for a
Person.__init__(self,name,'mgr')
function. Can use a lambda or function to generate the values too. **only redef ine constructor where it is needed
***MAPS AND LIST COMPREHENSIONS ARE FASTER***
Tom= Manager('Tom Jones', 50000) *no need to specify job
List Comprehension
**[M[row][col] * N[row][col] for row in range(3) for col in range(3)]** **All classes have the following meta methods**
*Parenthesis: Used to create a generator
Class.__dict__: class namespace
*Brackets: Used to Create a list
Class.__doc__: documentation string
Generators
Class.__name__: class name
*Generators make use of yield to output values one at a time and Class.__module__: module name where class def ined
avoids storage costs. Ephemeral values. Single iteration objects Class.__bases__: tuple of base classes
Example: ** x= gensquare(4)
next(x)
output=0
Def gensquare(N):
Common Operator Overloading
Common Operator Overloading
For I in range x:
__init__
constructor, object creation
__ior__ OR operator, store value in left var
yield x**2
__del__
destructor, object reclamation
__radd__
Used if __add__ fails
*Can use send() to pass a value outside of queue
__or__
operator, OR, |, |=
__iadd__
Operator, +=
Ex: x.send(4) output
0, 16
__add__
operator, +
__iter__, __next__
used for iteration
Time - Performance
__repr, __str__
printing or output
__contains__ membership test
Import timer
timer.total() OR timer.bestof()
__call__
call object instance as Function
__index__
Can use the Pystones module
__getattr__
fetch attribute, Ex: X.fetch
__enter__, __exit__
Modules
__setattr__
assign instance attribute
__get__, __set__
_init_.py
declares and initializes a regular module package
__delattr__
delete attribute. Ex: del X.any
__delete__
Descriptor attributes
*Modules should have unif ied purpose
__getattribute__
invoke before getattr*
__new__
-Helpful Module Internals: (Build programs about programs)__getitem__
extract item from iterable
Ex 1: Scipy.mean
__setitem__
place item in iterable
Ex 2: Scipy.__dict__['scipy']
__delattr__
delete item in iterable
Ex 3: sys.modules['scipy'].mean
__len__
get length
Ex 4: getattr(scipy, 'name')
__lt__,__gt__
comaprisons, >, <
*Can import using exec() command
exec(''import '+'scipy')
__le__, __ge__
comparisons, <=, >=
*Also use: imp = __import__('scipy') **faster
__eq__, __ne__
comparisons, ==, !=
*Also use: imp = scipy.import_module('mean')