美文网首页
python 黑色幽默

python 黑色幽默

作者: MrHamster | 来源:发表于2017-04-10 21:44 被阅读25次
    • 旧式类 VS 新式类

    Old:

    >>> class X():pass
    >>> print type(X())
    >>> <type 'instance'>
    

    New:

    >>> class X(object):pass
    >>> print type(X())
    >>> <class '__mian__.X'>
    

    Let's go

    >>> class X():pass
    >>> class Y():pass
    >>> print type(X()) == type(Y())
    >>> True
    >>> class X(object):pass
    >>> class Y(object):pass
    >>> print type(X()) == type(Y())
    >>> False
    
    • 内建函数

      • __missing__

      __getitem__ 调用.

      Let's go

            >>> class DefaultDict(dict):
            >>>   def __getitem__(self, key):
            >>>     print '__getitem__:', key
            >>>     return super(Dict , self).__getitem__(key)
            >>>   def __missing__(self, key):
            >>>     print '__missing__'
            >>> print DefaultDict()['a']
            >>> __getitem__: a
            >>> __missing__
            >>> None
            >>> dict()['a']      
            >>> KeyError: 'a'
      
    ### OtherWays
    `dict. setdefault(key[, default])` 也可以解决
    `class collections.defaultdict([default_factory[, ...]])`更好。
    
    ---
    To Be Continue

    相关文章

      网友评论

          本文标题:python 黑色幽默

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