美文网首页
[code snippet]优先级的妙用

[code snippet]优先级的妙用

作者: 顾慎为 | 来源:发表于2018-05-24 23:24 被阅读17次

    位置参数默认为None,但该参数默认是一个可迭代对象。如果不传参的话:

    In [8]: def func(iter_obj=None):
       ...:     for item in iter_obj:
       ...:         print item
       ...:
    
    In [9]: func()
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-9-08a2da4138f6> in <module>()
    ----> 1 func()
    
    <ipython-input-8-f880f4d9f102> in func(iter_obj)
          1 def func(iter_obj=None):
    ----> 2     for item in iter_obj:
          3         print item
          4
    
    TypeError: 'NoneType' object is not iterable
    

    通过优先级来对准备迭代的对象进行替换:

    In [10]: def func(iter_obj=None):
        ...:     for item in iter_obj or ():
        ...:         print item
        ...:
    
    In [11]: func()
    

    来源:werkzeug.routing.Map__init__方法:

    class Map(object):
        def __init__(self, rules=None, default_subdomain='', charset='utf-8',
                     strict_slashes=True, redirect_defaults=True,
                     converters=None, sort_parameters=False, sort_key=None,
                     encoding_errors='replace', host_matching=False):
           ...
    
            for rulefactory in rules or ():
                self.add(rulefactory)
    

    相关文章

      网友评论

          本文标题:[code snippet]优先级的妙用

          本文链接:https://www.haomeiwen.com/subject/pxbejftx.html