Python数据模型

  • Python解释器调用特殊方法来执行基本对象的操作,通常由特殊句法触发,其名称通常由两个下划线包围
  • Exp:
    • obj[key] = obj.__getitem__()
    • String Representation: __repr__ __str__ __format__ __bytes__
    • Conversion to number: __bool__ __complex__ __int__ __float__ __hash__
    • Emulating collections: __len__ __getitem__ __setitem__ __delitem__ __contains__
    • Iteration: __iter__ __aiter__ __next__ __anext__ __reversed__
    • Instance creation and destruction: __new__ __init__ __del__
    • Attribute management: __getattr__ __getattribute__ __setattr__ __delattr__ __dir__
  • Some useful explanation:
    • __dir__: return valid list of the attributes for the objects in current local scope
    • __getattr__ __getattribute__: getattr will not be call if getattribute defined
    • __bool__: if not implement, invoke __len__
    • Different Between __str__ __repr__:(__repr__(be unambiguous) > __str__(be readable))
      • The string returned by __repr__ should be unambiguous and, if possible, match the source code necessary to re-create the represented object
      • __str__ should return a string suitable for display to end users
      • Implement __repr__ for any class you implement. This should be second nature. Implement __str__ if you think it would be useful to have a string version which errs on the side of readability.
>>> class Sic(object): 
...   def __repr__(self): return 'foo'
... 
>>> print(str(Sic()))
foo
>>> print(repr(Sic()))
foo
>>> class Sic(object):
...   def __str__(self): return 'foo'
... 
>>> print(str(Sic()))
foo
>>> print(repr(Sic()))
<__main__.Sic object at 0x2617f0>
>>>