Ed.*_*Ed. 151
这些中有些重叠
Google Developers Day US - Python设计模式
另一个资源是Python Recipes的例子.一个好的数字不遵循最佳实践,但你可以找到一些有用的模式
Ano*_*ous 24
类型
>>> import this
在Python控制台中.
虽然这通常被视为一个(精细的!)笑话,但它包含一些有效的特定于python的公理.
lea*_*ncz 13
布鲁斯·埃克尔(Bruce Eckel)的" 思考Python "(Thinking in Python)严重依赖于设计模式
要深入了解设计模式,您应该查看设计模式:可重用面向对象软件的元素.源代码不在Python中,但不需要您了解模式.
在可能存在或可能不存在的对象上调用属性时,可以用来简化代码的东西是使用Null对象设计模式(我在Python Cookbook中介绍过).
粗略地说,Null对象的目标是为Python中常用的原始数据类型None或其他语言中的Null(或Null指针)提供"智能"替换.这些用于许多目的,包括重要的情况,其中一些其他类似元素的一个成员出于某种原因是特殊的.大多数情况下,这会导致条件语句区分普通元素和原始Null值.
这个对象只是缺少属性错误,你可以避免检查它们的存在.
它只不过是
class Null(object):
    def __init__(self, *args, **kwargs):
        "Ignore parameters."
        return None
    def __call__(self, *args, **kwargs):
        "Ignore method calls."
        return self
    def __getattr__(self, mname):
        "Ignore attribute requests."
        return self
    def __setattr__(self, name, value):
        "Ignore attribute setting."
        return self
    def __delattr__(self, name):
        "Ignore deleting attributes."
        return self
    def __repr__(self):
        "Return a string representation."
        return "<Null>"
    def __str__(self):
        "Convert to a string and return it."
        return "Null"
有了它,如果你这样做Null("any", "params", "you", "want").attribute_that_doesnt_exists()不会爆炸,但只是默默地成为相当于pass.
通常你会做类似的事情
if obj.attr:
    obj.attr()
有了这个,你只需:
obj.attr()
并忘掉它.请注意,对Null对象的广泛使用可能会隐藏代码中的错误.