Presentation is loading. Please wait.

Presentation is loading. Please wait.

 Name Space ◦ modname.funcname ◦ Main 의 module name: ‘__main__’ if __name__ == ‘__main__’:  Scopes.

Similar presentations


Presentation on theme: " Name Space ◦ modname.funcname ◦ Main 의 module name: ‘__main__’ if __name__ == ‘__main__’:  Scopes."— Presentation transcript:

1

2  Name Space ◦ modname.funcname ◦ Main 의 module name: ‘__main__’ if __name__ == ‘__main__’:  Scopes

3 try: f = open("myfile.txt") except IOError as e: print ‘cannot open:’, e else: for line in f: print line, f.close() finally: # always executed with open("myfile.txt") as f: for line in f: print line, f = open("myfile.txt") for line in f: print line, May raise exception Exception handling Pre-defined Clean-up f always closed!

4 >>> try:... raise Exception('spam', 'eggs')... except Exception as inst:... print type(inst) # the exception instance... print inst.args # arguments stored in.args... print inst # __str__ allows args to be printed directly... x, y = inst.args... print 'x =', x... print 'y =', y... ('spam', 'eggs') x = spam y = eggs >>> class MyError(Exception):... def __init__(self, value):... self.value = value... def __str__(self):... return repr(self.value)... >>> try:... raise MyError(2*2)... except MyError as e:... print 'My exception occurred, value:', e.value... My exception occurred, value: 4 >>> raise MyError('oops!') Traceback (most recent call last): File " ", line 1, in ? __main__.MyError: 'oops!' See Exception HierarchyException Hierarchy

5

6 import logging logging.basicConfig(filename='example.log',level=logging.DEBUG) logging.debug('This message should go to the log file') logging.info('So should this') logging.warning('And this, too') Output: DEBUG:root:This message should go to the log file INFO:root:So should this WARNING:root:And this, too LevelWhen it’s used loggin.debug()DEBUG Detailed information, typically of interest only when diagnosing problems. logging.info()INFOConfirmation that things are working as expected. logging.warning() WARNING (default level) An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. logging.error() logging.exception() ERROR Due to a more serious problem, the software has not been able to perform some function. Only called from exception handler logging.critical()CRITICAL A serious error, indicating that the program itself may be unable to continue running. Main 에서 선언하고 다른 module 에서는 Import 만 high sys.stderr default sys.stderr default

7 import logging from logging import DEBUG, INFO, WARNING, ERROR def setup_server_logging(name='', logfile='', maxBytes=524288, backupCount=1, level=logging.DEBUG, fmt='%(asctime)s %(name)s %(levelname)s %(message)s'): logger = logging.getLogger('') logger.setLevel(level) ch = logging.handlers.RotatingFileHandler(logfile, maxBytes, backupCount) ch.setLevel(level) formatter = logging.Formatter(fmt) ch.setFormatter(formatter) logger.addHandler(ch) return logger def setup_console_logging(name='', level=logging.DEBUG, fmtt='%(name)s %(levelname)s %(message)s'): """Convenience function for setting up simple logging to console.""" logger = logging.getLogger('') logger.setLevel(level) ch = logging.StreamHandler() ch.setLevel(level) formatter = logging.Formatter(fmt) ch.setFormatter(formatter) logger.addHandler(ch) return logger

8 >>> import time >>> time.time() 1432810215.638 >>> time_struct = time.localtime() >>> time_struct time.struct_time(tm_year=2015, tm_mon=5, tm_mday=28, tm_hour=19, tm_min=50, tm_sec=28, tm_wday=3, tm_yday=148, tm_isdst=0) >>> tuple(time_struct) (2015, 5, 28, 19, 50, 28, 3, 148, 0) >>> time.asctime(time_struct) 'Thu May 28 19:50:28 2015' >>> time.gmtime() time.struct_time(tm_year=2015, tm_mon=5, tm_mday=28, tm_hour=10, tm_min=51, tm_sec=13, tm_wday=3, tm_yday=148, tm_isdst=0) >>> begin = time.time(); time.sleep(5); now = time.time() >>> elapsed = now – begin >>> elapsed 5.000999927520752

9 Call by Reference Mutable objects passed may be changed

10 def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError('refusenik user') print complaint ask_ok('Do you really want to quit?') ask_ok('OK to overwrite the file?', 2) ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!') # with positional and keyword arguments ask_ok('OK to overwrite the file?', complaint='Come on, only yes or no!’, retries=2)

11 >>> # *args: arbitrary # of parameters >>> def my_sum(*args): sum = 0 for arg in args: # args: a tuple sum += arg return sum >>> my_sum(1, 2, 3, 4, 5) 15 >>> t = (1, 2, 3, 4, 5) >>> my_sum(t[0], t[1], t[2], t[3], t[4]) 15 >>> my_sum(*t) # unpacking arg list 15 >>> >>> def my_sum(args): # a tuple or list sum = 0 for arg in args: sum += arg return sum >>> t = (1, 2, 3, 4, 5) >>> my_sum(t) 15 >>> my_sum(1, 2, 3, 4, 5) Traceback (most recent call last): File " ", line 1, in my_sum(1,2,3,4,5) TypeError: my_sum() takes exactly 1 argument (5 given) >>>

12 >>> def cheeseshop(kind, *arguments, **keywords): print "-- Do you have any", kind, "?" print "-- I'm sorry, we're all out of", kind for arg in arguments: print arg print "-" * 40 keys = sorted(keywords.keys()) for kw in keys: print kw, ":", keywords[kw] >>> cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper='Michael Palin', client="John Cleese", sketch="Cheese Shop Sketch") -- Do you have any Limburger ? -- I'm sorry, we're all out of Limburger It's very runny, sir. It's really very, VERY runny, sir. ---------------------------------------- client : John Cleese shopkeeper : Michael Palin sketch : Cheese Shop Sketch

13

14 # initdata.py # records bob = {'name': 'Bob Smith', 'age': 42, 'pay': 30000, 'job': 'dev'} sue = {'name': 'Sue Jones', 'age': 45, 'pay': 40000, 'job': 'hdw'} tom = {'name': 'Tom', 'age': 50, 'pay': 0, 'job': None} # database db = {} db['bob'] = bob db['sue'] = sue db['tom'] = tom if __name__ == '__main__': # when run as a script for key in db: print key, '=>\n ', db[key]

15 class Person: def __init__(self, name, age, pay=0, job=None): self.name = name self.age = age self.pay = pay self.job = job def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay *= (1.0 + percent) class Manager(Person): def __init__(self, name, age, pay): Person.__init__(self, name, age, pay, 'manager') def giveRaise(self, percent, bonus=0.1): Person.giveRaise(self, percent + bonus) if __name__ == '__main__': bob = Person('Bob Smith', 44) sue = Person('Sue Jones', 47, 40000, 'hardware') tom = Manager(name='Tom Doe', age=50, pay=50000) print sue, sue.pay, sue.lastName() for obj in (bob, sue, tom): obj.giveRaise(.10) print obj

16  supports most of the same functionality as dictionaries  modified objects are written only when assigned to the shelf  the values (not the keys!) in a shelf can be essentially arbitrary Python objects from initdata import bob, sue import shelve db = shelve.open('people-shelve') db['bob'] = bob db['sue'] = sue db.close() from initdata import tom import shelve db = shelve.open('people-shelve') sue = db['sue'] sue['pay'] *= 1.50 db['sue'] = sue db['tom'] = tom db.close() flagMeaning 'r'Open existing database for reading only 'w'Open existing database for reading and writing 'c'Open database for reading and writing, creating it if it doesn’t exist (default) 'n'Always create a new, empty database, open for reading and writing


Download ppt " Name Space ◦ modname.funcname ◦ Main 의 module name: ‘__main__’ if __name__ == ‘__main__’:  Scopes."

Similar presentations


Ads by Google