python 黑色幽默

  • 旧式类 VS 新式类

Old:

>>> class X():pass
>>> print type(X())
>>> 

New:

>>> class X(object):pass
>>> print type(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 黑色幽默)