background preloader

Understanding Python's "with" statement

Understanding Python's "with" statement
Fredrik Lundh | October 2006 | Originally posted to online.effbot.org Judging from comp.lang.python and other forums, Python 2.5’s new with statement (dead link) seems to be a bit confusing even for experienced Python programmers. As most other things in Python, the with statement is actually very simple, once you understand the problem it’s trying to solve. Consider this piece of code: set things up try: do something finally: tear things down Here, “set things up” could be opening a file, or acquiring some sort of external resource, and “tear things down” would then be closing the file, or releasing or removing the resource. If you do this a lot, it would be quite convenient if you could put the “set things up” and “tear things down” code in a library function, to make it easy to reuse. def controlled_execution(callback): set things up try: callback(thing) finally: tear things down def my_function(thing): do something controlled_execution(my_function) This wasn’t very difficult, was it? Related:  programming

python中的异常 - 如果你想看看某人的灵魂,只要问问他做了什么梦就行了 当你的程序中出现异常情况时就需要异常处理。比如当你打开一个不存在的文件时。当你的程序中有一些无效的语句时,Python会提示你有错误存在。 下面是一个拼写错误的例子,print写成了Print。 >>> Print 'Hello World' File "", line 1 Print 'Hello World' ^ SyntaxError: invalid syntax >>> print 'Hello World' Hello World 1、try...except语句 try...except语句可以用于捕捉并处理错误。 #! 运行输出如下: $ python try_except.py Enter something --> Why did you do an EOF on me? 说明:每个try语句都必须有至少一个except语句。 2、引发异常 你可以用raise语句来引发一个异常。 #! $ python raising.py 请输入 --> 你输入了一个结束标记EOF $ python raising.py 请输入 --> --> ab ShortInputException: 输入的长度是 2, 长度至少应是 3 $ python raising.py 请输入 --> abc 没有异常发生. 3、try...finally语句 当你正在读文件或还未关闭文件时发生了异常该怎么办呢? #! $ python finally.py Programming is fun When the work is done Cleaning up...closed the file Traceback (most recent call last): File "finally.py", line 12, in ? 说明:我们在两秒这段时间内按下了Ctrl-c,这将产生一个KeyboardInterrupt异常,我们并没有处理这个异常,那么Python将调用默认的处理器,并终止程序,在程序终止之前,finally块中的语句将执行。 本系列的文章来源是

A guide to Python's function decorators Python is rich with powerful features and expressive syntax. One of my favorites is decorators. In the context of design patterns, decorators dynamically alter the functionality of a function, method or class without having to directly use subclasses. This is ideal when you need to extend the functionality of functions that you don't want to modify. We can implement the decorator pattern anywhere, but Python facilitates the implementation by providing much more expressive features and syntax for that. In this post I will be discussing Python's function decorators in depth, accompanied by a bunch of examples on the way to clear up the concepts. Essentially, decorators work as wrappers, modifying the behavior of the code before and after a target function execution, without the need to modify the function itself, augmenting the original functionality, thus decorating it. What you need to know about functions Before diving in, there are some prerequisites that should be clear. Phew!

HowTo/Sorting Original version by Andrew Dalke with a major update by Raymond Hettinger Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable. There are many ways to use them to sort data and there doesn't appear to be a single, central place in the various manuals describing them, so I'll do so here. Sorting Basics A simple ascending sort is very easy -- just call the sorted() function. >>> sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5] You can also use the list.sort() method of a list. >>> a = [5, 2, 3, 1, 4] >>> a.sort() >>> a [1, 2, 3, 4, 5] Another difference is that the list.sort() method is only defined for lists. Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons. For example, here's a case-insensitive string comparison: The same technique works for objects with named attributes.

Python异常处理_aimee Python的异常处理能力是很强大的,可向用户准确反馈出错信息。在Python中,异常也是对象,可对它进行操作。所有异常都是基类Exception的成员。所有异常都从基类Exception继承,而且都在exceptions模块中定义。Python自动将所有异常名称放在内建命名空间中,所以程序不必导入exceptions模块即可使用异常。 方式一:try语句: 1使用try和except语句来捕获异常 try: block except [exception,[data…]]: block try: block except [exception,[data...]]: block else: block 该种异常处理语法的规则是: · 执行try下的语句,如果引发异常,则执行过程会跳到第一个except语句。 · 如果第一个except中定义的异常与引发的异常匹配,则执行该except中的语句。 · 如果引发的异常不匹配第一个except,则会搜索第二个except,允许编写的except数量没有限制。 · 如果所有的except都不匹配,则异常会传递到下一个调用本代码的最高层try代码中。 · 如果没有发生异常,则执行else块代码。 例: try: f = open(“file.txt”,”r”) except IOError, e: print e 捕获到的IOError错误的详细原因会被放置在对象e中,然后运行该异常的except代码块 捕获所有的异常 try: a=b b=c except Exception,ex: print Exception,":",ex 使用except子句需要注意的事情,就是多个except子句截获异常时,如果各个异常类之间具有继承关系,则子类应该写在前面,否则父类将会直接截获子类异常。 2 使用try跟finally: 语法如下: try: block finally: block 该语句的执行规则是: · 执行try下的代码。 · 如果发生异常,在该异常传递到下一级try时,执行finally中的代码。 · 如果没有发生异常,则执行finally中的代码。 第二种try语法在无论有没有发生异常都要执行代码的情况下是很有用的。 这两种形式相互冲突,使用了一种就不允许使用另一种,而功能又各异 2. raise [exception[,data]] 3. 格式: 4. 或者以如下的形式:

跳出面向对象思想(二) 多态 - Casa Taloyum 多态一般都要跟继承结合起来说,其本质是子类通过覆盖或重载(在下文里我会多次用到覆盖或重载,我打算把它简化成覆重,意思到就好,不要太纠结这种名词。)父类的方法,来使得对同一类对象同一方法的调用产生不同的结果。这里需要辨析的地方在:同一类对象指的是继承层级再上一层的对象,更加泛化。 举个例子: Animal -> Cat Animal -> Dog Animal.speak() // I'm an Animal Cat.speak() // I'm a Cat Dog.speak() // I'm a Dog 此处Cat和Dog虽然不是同一种对象,但它们算是同一类对象,因为他们的父类都是Animal。 ^ 表示他们是同一类 ^^ 表示他们同种同类 Animal -> Cat Animal -> Dog Cat kitty, kate Dog lucky, lucy 我们可以这么说: kitty ^^ kate 同种同类,他们都是猫 kitty ^ lucy 同类不同种,他们都是Animal kitty ! 应该算是能够描述清楚了吧? 一般来说我们采用多态的场景还是很多的,有些在设计的时候就是用于继承的父类,希望子类覆盖自己的某些方法,然后才能够使程序正常运行下去。 BaseController需要它的子类去覆盖loadView等方法来执行view的显示逻辑 BaseApiManager需要它的子类去覆盖methodName等方法来执行具体的API请求 以上是我列举的应用多态的几个场景,在基于上面提到的需求,以及站在代码观感的立场,我们在实际采用多态的时候会有下面四种情况: 父类有部分public的方法是不需要,也不允许子类覆重父类有一些特别的方法是必须要子类去覆重的,在父类的方法其实是个空方法父类有一些方法是可选覆重的,一旦覆重,则以子类为准父类有一些方法即便被覆重,父类原方法还是要执行的 这四种情况在大多数支持多态的语言里面都没有做很好的原生限制,在程序规模逐渐变大的时候,会给维护代码的程序员带来各种各样的坑。 父类有部分public的方法是不需要,也不允许子类覆重 对于客户程序员来说,他们是有动机去覆重那些不需要覆重的方法的,比如需要在某个方法调用的时候做UserTrack,或者希望在方法调用之前做一些额外的事情,但是又找不到外面应该在哪儿做,于是就索性覆重一个了。 前者太累,后者太蠢。

5.3. Defining Classes Python is fully object-oriented: you can define your own classes, inherit from your own or built-in classes, and instantiate the classes you've defined. Defining a class in Python is simple. As with functions, there is no separate interface definition. Just define the class and start coding. A Python class starts with the reserved word class, followed by the class name. Example 5.3. class Loaf: pass Of course, realistically, most classes will be inherited from other classes, and they will define their own class methods and attributes. Example 5.4. from UserDict import UserDict class FileInfo(UserDict): Python supports multiple inheritance. 5.3.1. This example shows the initialization of the FileInfo class using the __init__ method. Example 5.5. class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): 5.3.2. When defining your class methods, you must explicitly list self as the first argument for each method, including __init__. Whew.

使用NotePad++编辑python代码_简简单单 以前用过emacs编辑过python代码,虽然那个Tab一键完成比较爽,但是emacs配置太麻烦(windows下),而且还会产生.file#之类的文件,看着就心烦!前天弄了一下notepad++,觉得相当不错! 以下文章转载自:萧萧—sina博客 Notepad++ 是一个开源的文本编辑器,功能强大而且使用方便。 我是在 PortableApps.com 上下载的 Notepad++ Portable ,它的好处是可以在每次关闭程序的时候把所需的配置文件单独保存,省却每台机器上重新配置的烦恼。 Tab长度和空格转换 因为 Python 对缩进要求严格,我们将 Tab 设置成4个空格,在 "设置->首选项->编辑->制表符设置" 中修改。 语法高亮 只要正确设置了扩展名,Notepad++ 就会自动识别语言并进行语法高亮。 自动完成 Notepad++ 也提供了自动完成和输入提示功能,在 "设置->首选项->备份与自动完成" 中可以设置。 运行程序 点击 "运行->运行" (默认快捷键是 F5 ),在弹出的菜单中输入: cmd /k C:/Python30/python.exe "$(FULL_CURRENT_PATH)" & PAUSE & EXIT 选择 "保存",就可以给这条命令设置一个快捷键并起一个名字,比如叫 "Run Python"。 如果想修改这条命令,目前只能通过修改 shortcuts.xml 文件,这个文件保存在 Notepad++ 的配置文件中,可能在 Notepad++ 的目录,也可能在 Documents and Settings 下的 Application Data 内。

Django templates · Django Girls Tutorial Time to display some data! Django gives us some helpful built-in template tags for that. You see, in HTML, you can't really write Python code, because browsers don't understand it. They know only HTML. We know that HTML is rather static, while Python is much more dynamic. Django template tags allow us to transfer Python-like things into HTML, so you can build dynamic websites faster and easier. Display post list template In the previous chapter we gave our template a list of posts in the posts variable. To print a variable in Django templates, we use double curly brackets with the variable's name inside, like this: blog/templates/blog/post_list.html {{ posts }} Try this in your blog/templates/blog/post_list.html template. As you can see, all we've got is this: [<Post: My second post>, <Post: My first post>] This means that Django understands it as a list of objects. {% for post in posts %} {{ post }} {% endfor %} Try this in your template. It works! One more thing First, push your code to Github

Understanding Python Iterables and Iterators | Shut Up and Ship Decorators have been in Python since version 2.4. They are the lines that start with @ symbol just before a function or a class definition. Probably you encountered them when you defined class methods, properties etc. Or perhaps you encountered them in a web framework like Django and used them to magically add login requirements for certain pages by adding a @login_required line before your view function. Decorator formalities First let us deal with the formalities like definition, syntax, etc. Here is the template of a decorator without arguments. @decoratordef F(arg): pass # is same asdef F(arg): passF = decorator(f) And here is a decorator with arguments. @decorator(n)def F(arg): pass # is same asdef F(arg): passF = decorator(n)(F) As you can see, strictly speaking we don’t need the decorator syntax. Writing our own decorators Here are a couple of functions in our module. def simpleinterest(n, p, r): return n*p*r/100.0 def compoundinterest(n, p, r): return p*(1+r/100.0)**n-p It works!

Notepad++编辑Pyhton文件的自动缩进的问题(图文)(转) - ksharp_dabu的日志 Ps:notepad++还有很多功能不知道,自己也没安装什么插件,以后看来要和它多打交道了。 原文链接: 这个问题一直困扰我很久,Python对缩进很敏感,一般建议缩进用空格,而Notepad++的自动缩进是用的TAB,google过,baidu过, 都提到在首选项中有个将TAB用4个空格代替的选项,可我一直找不到这个选项,经过N个版本更新后依然如初,甚至还下载过一些插件希望能解决,但无果。 今天终于在帮助文档中找到答案了(HELP很重要啊!!!),特记录之,免日久又忘掉。 如果你想打开自动缩进,可以在 设置-》首选项-》其他 中进行设置 勾选了这个后,你换行是就会自动缩进了,下面还要设置将TAB更换成4个空格 设置-》首选项-》语言-》标签设置 不要改“Default”,现在做得很灵活了,可以对不同的语言进行设置,我们可以选上Pyhton,将默认去掉,选“以空格取代” 现在你的Notepad++可以很好的编辑Pyhton文件了 随便说说运行的设置,在运行(F5)中输入 cmd /k C:\Python26\python.exe "$(FULL_CURRENT_PATH)" & PAUSE & EXIT , 注意:上面的输入相当于在cmd运行python.exe的绝对路径,所以你要根据自己的python的路径修改就性了。 点击保存,自己起个名字,以后在“运行”菜单下就可以运行你的Python程序了

Related: