备忘
_(下划线)
If you enter an expression, the resulting value will be printed to the console. The
result of the last expression, whether value orobject, is available in the interpreter by
using the underscore (_).If you can’t find a calculator, then you can always turn to the
Python interpreter instead.
>>> 1.2 * (64 / 2.4) + 36 +2 ** 5 100.0 >>> _ 100.0 >>> x = _ >>> print x 100.0
_:当上一条表达的值是有效的,可用_代替上一条表达式的值
string的判断
Both strand unicodestrings have a common base class: basestring. If you want
to check if an object is a string and you don’t care which type of string, you can use
isinstance(someObject, basestring). This isn’t important for IronPython, but can
be useful for compatibility with CPython.
关于Flase
In Boolean terms, the following objects are considered to be False:
■ Falseand None
■ 0 (integer, long, or float)
■ An empty string (byte-string or Unicode)
■ An empty list, tuple, set, or dictionary
Everything else is considered True.
>>> x = {} >>> if not x: ... print 'Not this one' ... Not this one >>> y = [1] >>> if y: ... print 'This one' ... This one
关于异常
finally, except, and the with statement
In Python 2.4 (IronPython 1),
you can’t have an exceptclause and a finally
clause in the same block.
In Python 2.5 (IronPython 2), you can have both exceptclauses and a finally
clause in the same block. If an exception is caught by an exceptclause, the code in
the finallyclause is still executed.
Another common pattern used in Python 2.5, which can often replace use of finally,
is to use the with statement. This is similar to the using statement in C#, and allows
you to use a resource with its cleanup guaranteed even if an exception is raised.
列表过滤
>>> input = [1, 2, 3, 4, 5] >>> result = [value * 3 for value in input if value > 2] >>> result [9, 12, 15] >>>
standard library
Exception(异常类)
When you catch the exception, the instance of IOErrorraised will carry a message tell
ing you what went wrong. You can turn the exception instance into a string by using
the built in strfunction. The following code segment tries to save a file with a bogus
filename—unless you have this file on drive z, that is! It catches the ensuing error and
reports it by printing the error message:
>>> from System.IO import StreamWriter >>> filename = 'z:\\NonExistentFile.txt' >>> try: ... writer = StreamWriter(filename) ... except IOError, e: ... print 'Something went wrong.' ... print 'The error was:\r\n%s' % str(e) ... Something went wrong. The error was: Could not find a part of the path 'z:\NonExistentFile.txt'
lambda表达式