from base import APIBase from client import Client from decorator import interface, export, stream from server import Server from storage import Storage from util import (LogFormatter, disable_logging_to_stderr, enable_logging_to_kids, info)
def __exit__(self, exc_type, exc_value, exc_traceback): print "__exit__ method" if exc_traceback is None: print "Exited without Exception" return True else: print "Exited with Exception" return False
def test_with(): with MyWith() as my_with: print "running my_with" print "------分割线-----" with MyWith() as my_with: print "running before Exception" raise Exception print "running after Exception"
if __name__ == '__main__': test_with()
执行结果如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
__init__ method __enter__ method running my_with __exit__ method Exited without Exception ------分割线----- __init__ method __enter__ method running before Exception __exit__ method Exited with Exception Traceback (most recent call last): File "bin/python", line 34, in <module> exec(compile(__file__f.read(), __file__, "exec")) File "test_with.py", line 33, in <module> test_with() File "test_with.py", line 28, in test_with raise Exception Exception
@score.setter #相当于score = property.setter(score) def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value
getattr(object, name[, default])Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, ‘foobar’) is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
defprocess_command_line(argv): """ Return a 2-tuple: (settings object, args list). `argv` is a list of arguments, or `None` for ``sys.argv[1:]``. """ if argv isNone: argv = sys.argv[1:]
# initialize the parser object: parser = optparse.OptionParser( formatter=optparse.TitledHelpFormatter(width=78), add_help_option=None)
# define options here: parser.add_option( # customized description; put --help last '-h', '--help', action='help', help='Show this help message and exit.')
settings, args = parser.parse_args(argv)
# check number of arguments, verify values, etc.: if args: parser.error('program takes no command-line arguments; ' '"%s" ignored.' % (args,))