180 likes | 259 Views
Documentation / References. Python Full Documentation http://docs.python.org/index.html Python Quick Reference http://rgruet.free.fr/ IPython <object>? help <object> tab completion. Basics. Tabbing is crucial and mandatory DO NOT mix tabs with spaces, choose one method and stick to it
E N D
Documentation / References • Python Full Documentation • http://docs.python.org/index.html • Python Quick Reference • http://rgruet.free.fr/ • IPython • <object>? • help <object> • tab completion
Basics • Tabbing is crucial and mandatory • DO NOT mix tabs with spaces, choose one method and stick to it • Comments: • # single line comment • """ long comment """ • Philosophic mindset • Shorter and simpler is better, without getting cryptic • Intuitive to existing programmers • No deliberate way to do the same code in two different ways • Keywords • None • True • False • pass
Duck Typing • “when I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.” - James Whitcomb Riley • Casting: • int(variable) • int('FF', 16) == 255 • float(variable) • also definable by adding a period • str(variable) • Type Comparison • type(variable) == type([]) • type(variable) == type(“”) • type(variable) == type(0)
Data Types • Modules • Objects • Integer • Float • Strings • List • Dictionary • Tuple • Decorators • Generators
Modules • Two methods of importing • import math • Now, functions or attributes defined in math can be accessed like so: math.pi, math.sin(), etc. • from math import * • Now, all of math is imported into the global namespace and can be accessed like so: pi, sin(), etc. • from math import pi • Now, only pi is in the global namespace
Numbers • Types: • Integers • Floats • Infinite length • Math • ( + - * / % ^ & | ) • ** instead of ^ (but ^ exists as XOR, be careful) • += exists, but ++ does not (use +=1) • More math • import math • math.e, math.pi, math.cos(), math.acos(), math.cosh(), math.log(), math.ceil(), math.sqrt()
Control Flow Statements • if, elif, else… and, or, not • while • continue • break • for • More like foreach in other languages • try, except list = [2, 3, 1, 7] i = 0 while i < len(list): print "output:", str(i) i += 1 output: 2 output: 3 output: 1 output: 7 list = [2, 3, 1, 7] for x in list: print "output:”, str(x) output: 2 output: 3 output: 1 output: 7 try: dict_array[0]['item’] # code for success except IndexError: # code if [0] fails except KeyError: # code if ['item'] fails if len(dict_array) == 0: # code if [0] fails elifdict_array.has_key('item‘): # code if ['item'] fails else: # code for success
switch Control Structure • There isn’t one. • Alternatives to switch: • if, elif, else • dictionary forms {'one': lambda x: x+1, 'two': lambda x: x+2, 'three': lambda x: x+3 }[var](var) if var == 'one': # do 'one' specific code elifvar == 'two': # do 'two' specific code elifvar == 'three': # do 'three' specific code else: # do default code def one_code(): # do 'one' specific code def two_code(): # do 'two' specific code def three_code(): # do 'three' specific code def default_code(): # do default code {'one': one_code, 'two': two_code, 'three': three_code}[var]()
Strings • Defined in usual ways • Important Methods: • strip() • join() • split() • String formatting (like printf) mystr = " first second third" myarr = mystr.strip().split(" ") for i in xrange(0, len(myarr)): print "output:", myarr[i] print "mystr::%s::" % " ".join(myarr) output: first output: second output: third mystr::first second third::
Lists • Important methods • append() • extend() • insert() • pop() list = [3, 4, 5] print "pop: %d" % list.pop(1) list.insert(0, 2) list.append(6) list.extend([7, 8]) print "list: %s" % str(list) pop: 4 list: [2, 3, 5, 6, 7, 8]
Slicing • A more complex way of handling list items and strings list = [2, 3, 1, 7, 5] print list print list[1:2] print list[2:] print list[-2:] print list[:-2] [2, 3, 1, 7, 5] [3] [1, 7, 5] [7, 5] [2, 3, 1]
Tuple • Collection of a fixed amount of values • Tuple unpacking def output_three_multiples(self, number): return (number*2, number*3, number*4) (first,second,_) = output_three_multiples(7)
File Manipulation • First thing that made me like Python file = open("filename", "r") contents = file.read() file.close() print contents file = open("filename", "r") contents = file.readlines() file.close() line_num = 1 for line in contents: print "%d: %s" % (line_num, line) line_num += 1
Classes • Everything involving classes in Python is weird • All classes extend "object" • Like Java • Historically this was not the case, so be careful • Constructor is: def __init__(self): • Private methods prefixed with two underscores • Static methods use @staticmethod decorator • Super methods are weird, too
Class Code import attrdict import errors from execute import * class server(attrdict): def __init__(self, dict): super(server, self).__init__(dict) # no executer until a function makes one self.executer = None def __do_execute(self, cmd): ret = self.require_remote() if ret: return (None,None,None) if self.executer: return self.executer.execute(cmd) else: return execute_srv(self.remote_server, cmd) def require_remote(self): if not self.require_dict(self.remote_server, [ "ip", "port" ]): return errors.throw(errors.BACKEND_INVALID_INPUT)
Class Code 2 import errors, glob, server from execute import * class master(server): def __init__(self, dict): super(master, self).__init__(dict) @staticmethod def __do_execute(cmd): return execute(cmd) def remove_key(self): ret = self.require_remote() if ret: return ret # strip keys from remote server (exit_code,_,_) = self.__do_execute( "ssh -i %s " % glob.config.get("paths", "master_private_key") + "-p " + str(self.remote_server['port']) + " root@" + self.remote_server['ip'] + " " + "\"sed -r \\\"/^.*_panenthe$/d\\\" -i %s\"" % glob.config.get("paths", "user_ssh_authorized_keys") ) # fail if exit_code != 0: return errors.throw(errors.SERVER_REMOTE_REMOVE) # return return errors.throw(errors.ERR_SUCCESS)