-
旧式类 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
网友评论